1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
  266
  267
  268
  269
  270
  271
  272
  273
  274
  275
  276
  277
  278
  279
  280
  281
  282
  283
  284
  285
  286
  287
  288
  289
  290
  291
  292
  293
  294
  295
  296
  297
  298
  299
  300
  301
  302
  303
  304
  305
  306
  307
  308
  309
  310
  311
  312
  313
  314
  315
  316
  317
  318
  319
  320
  321
  322
  323
  324
  325
  326
  327
  328
  329
  330
  331
  332
  333
  334
  335
  336
  337
  338
  339
  340
  341
  342
  343
  344
  345
  346
  347
  348
  349
  350
  351
  352
  353
  354
  355
  356
  357
  358
  359
  360
  361
  362
  363
  364
  365
  366
  367
  368
  369
  370
  371
  372
  373
  374
  375
  376
  377
  378
  379
  380
  381
  382
  383
  384
  385
  386
  387
  388
  389
  390
  391
  392
  393
  394
  395
  396
  397
  398
  399
  400
  401
  402
  403
  404
  405
  406
  407
  408
  409
  410
  411
  412
  413
  414
  415
  416
  417
  418
  419
  420
  421
  422
  423
  424
  425
  426
  427
  428
  429
  430
  431
  432
  433
  434
  435
  436
  437
  438
  439
  440
  441
  442
  443
  444
  445
  446
  447
  448
  449
  450
  451
  452
  453
  454
  455
  456
  457
  458
  459
  460
  461
  462
  463
  464
  465
  466
  467
  468
  469
  470
  471
  472
  473
  474
  475
  476
  477
  478
  479
  480
  481
  482
  483
  484
  485
  486
  487
  488
  489
  490
  491
  492
  493
  494
  495
  496
  497
  498
  499
  500
  501
  502
  503
  504
  505
  506
  507
  508
  509
  510
  511
  512
  513
  514
  515
  516
  517
  518
  519
  520
  521
  522
  523
  524
  525
  526
  527
  528
  529
  530
  531
  532
  533
  534
  535
  536
  537
  538
  539
  540
  541
  542
  543
  544
  545
  546
  547
  548
  549
  550
  551
  552
  553
  554
  555
  556
  557
  558
  559
  560
  561
  562
  563
  564
  565
  566
  567
  568
  569
  570
  571
  572
  573
  574
  575
  576
  577
  578
  579
  580
  581
  582
  583
  584
  585
  586
  587
  588
  589
  590
  591
  592
  593
  594
  595
  596
  597
  598
  599
  600
  601
  602
  603
  604
  605
  606
  607
  608
  609
  610
  611
  612
  613
  614
  615
  616
  617
  618
  619
  620
  621
  622
  623
  624
  625
  626
  627
  628
  629
  630
  631
  632
  633
  634
  635
  636
  637
  638
  639
  640
  641
  642
  643
  644
  645
  646
  647
  648
  649
  650
  651
  652
  653
  654
  655
  656
  657
  658
  659
  660
  661
  662
  663
  664
  665
  666
  667
  668
  669
  670
  671
  672
  673
  674
  675
  676
  677
  678
  679
  680
  681
  682
  683
  684
  685
  686
  687
  688
  689
  690
  691
  692
  693
  694
  695
  696
  697
  698
  699
  700
  701
  702
  703
  704
  705
  706
  707
  708
  709
  710
  711
  712
  713
  714
  715
  716
  717
  718
  719
  720
  721
  722
  723
  724
  725
  726
  727
  728
  729
  730
  731
  732
  733
  734
  735
  736
  737
  738
  739
  740
  741
  742
  743
  744
  745
  746
  747
  748
  749
  750
  751
  752
  753
  754
  755
  756
  757
  758
  759
  760
  761
  762
  763
  764
  765
  766
  767
  768
  769
  770
  771
  772
  773
  774
  775
  776
  777
  778
  779
  780
  781
  782
  783
  784
  785
  786
  787
  788
  789
  790
  791
  792
  793
  794
  795
  796
  797
  798
  799
  800
  801
  802
  803
  804
  805
  806
  807
  808
  809
  810
  811
  812
  813
  814
  815
  816
  817
  818
  819
  820
  821
  822
  823
  824
  825
  826
  827
  828
  829
  830
  831
  832
  833
  834
  835
  836
  837
  838
  839
  840
  841
  842
  843
  844
  845
  846
  847
  848
  849
  850
  851
  852
  853
  854
  855
  856
  857
  858
  859
  860
  861
  862
  863
  864
  865
  866
  867
  868
  869
  870
  871
  872
  873
  874
  875
  876
  877
  878
  879
  880
  881
  882
  883
  884
  885
  886
  887
  888
  889
  890
  891
  892
  893
  894
  895
  896
  897
  898
  899
  900
  901
  902
  903
  904
  905
  906
  907
  908
  909
  910
  911
  912
  913
  914
  915
  916
  917
  918
  919
  920
  921
  922
  923
  924
  925
  926
  927
  928
  929
  930
  931
  932
  933
  934
  935
  936
  937
  938
  939
  940
  941
  942
  943
  944
  945
  946
  947
  948
  949
  950
  951
  952
  953
  954
  955
  956
  957
  958
  959
  960
  961
  962
  963
  964
  965
  966
  967
  968
  969
  970
  971
  972
  973
  974
  975
  976
  977
  978
  979
  980
  981
  982
  983
  984
  985
  986
  987
  988
  989
  990
  991
  992
  993
  994
  995
  996
  997
  998
  999
 1000
 1001
 1002
 1003
 1004
 1005
 1006
 1007
 1008
 1009
 1010
 1011
 1012
 1013
 1014
 1015
 1016
 1017
 1018
 1019
 1020
 1021
 1022
 1023
 1024
 1025
 1026
 1027
 1028
 1029
 1030
 1031
 1032
 1033
 1034
 1035
 1036
 1037
 1038
 1039
 1040
 1041
 1042
 1043
 1044
 1045
 1046
 1047
 1048
 1049
 1050
 1051
 1052
 1053
 1054
 1055
 1056
 1057
 1058
 1059
 1060
 1061
 1062
 1063
 1064
 1065
 1066
 1067
 1068
 1069
 1070
 1071
 1072
 1073
 1074
 1075
 1076
 1077
 1078
 1079
 1080
 1081
 1082
 1083
 1084
 1085
 1086
 1087
 1088
 1089
 1090
 1091
 1092
 1093
 1094
 1095
 1096
 1097
 1098
 1099
 1100
 1101
 1102
 1103
 1104
 1105
 1106
 1107
 1108
 1109
 1110
 1111
 1112
 1113
 1114
 1115
 1116
 1117
 1118
 1119
 1120
 1121
 1122
 1123
 1124
 1125
 1126
 1127
 1128
 1129
 1130
 1131
 1132
 1133
 1134
 1135
 1136
 1137
 1138
 1139
 1140
 1141
 1142
 1143
 1144
 1145
 1146
 1147
 1148
 1149
 1150
 1151
 1152
 1153
 1154
 1155
 1156
 1157
 1158
 1159
 1160
 1161
 1162
 1163
 1164
 1165
 1166
 1167
 1168
 1169
 1170
 1171
 1172
 1173
 1174
 1175
 1176
 1177
 1178
 1179
 1180
 1181
 1182
 1183
 1184
 1185
 1186
 1187
 1188
 1189
 1190
 1191
 1192
 1193
 1194
 1195
 1196
 1197
 1198
 1199
 1200
 1201
 1202
 1203
 1204
 1205
 1206
 1207
 1208
 1209
 1210
 1211
 1212
 1213
 1214
 1215
 1216
 1217
 1218
 1219
 1220
 1221
 1222
 1223
 1224
 1225
 1226
 1227
 1228
 1229
 1230
 1231
 1232
 1233
 1234
 1235
 1236
 1237
 1238
 1239
 1240
 1241
 1242
 1243
 1244
 1245
 1246
 1247
 1248
 1249
 1250
 1251
 1252
 1253
 1254
 1255
 1256
 1257
 1258
 1259
 1260
 1261
 1262
 1263
 1264
 1265
 1266
 1267
 1268
 1269
 1270
 1271
 1272
 1273
 1274
 1275
 1276
 1277
 1278
 1279
 1280
 1281
 1282
 1283
 1284
 1285
 1286
 1287
 1288
 1289
 1290
 1291
 1292
 1293
 1294
 1295
 1296
 1297
 1298
 1299
 1300
 1301
 1302
 1303
 1304
 1305
 1306
 1307
 1308
 1309
 1310
 1311
 1312
 1313
 1314
 1315
 1316
 1317
 1318
 1319
 1320
 1321
 1322
 1323
 1324
 1325
 1326
 1327
 1328
 1329
 1330
 1331
 1332
 1333
 1334
 1335
 1336
 1337
 1338
 1339
 1340
 1341
 1342
 1343
 1344
 1345
 1346
 1347
 1348
 1349
 1350
 1351
 1352
 1353
 1354
 1355
 1356
 1357
 1358
 1359
 1360
 1361
 1362
 1363
 1364
 1365
 1366
 1367
 1368
 1369
 1370
 1371
 1372
 1373
 1374
 1375
 1376
 1377
 1378
 1379
 1380
 1381
 1382
 1383
 1384
 1385
 1386
 1387
 1388
 1389
 1390
 1391
 1392
 1393
 1394
 1395
 1396
 1397
 1398
 1399
 1400
 1401
 1402
 1403
 1404
 1405
 1406
 1407
 1408
 1409
 1410
 1411
 1412
 1413
 1414
 1415
 1416
 1417
 1418
 1419
 1420
 1421
 1422
 1423
 1424
 1425
 1426
 1427
 1428
 1429
 1430
 1431
 1432
 1433
 1434
 1435
 1436
 1437
 1438
 1439
 1440
 1441
 1442
 1443
 1444
 1445
 1446
 1447
 1448
 1449
 1450
 1451
 1452
 1453
 1454
 1455
 1456
 1457
 1458
 1459
 1460
 1461
 1462
 1463
 1464
 1465
 1466
 1467
 1468
 1469
 1470
 1471
 1472
 1473
 1474
 1475
 1476
 1477
 1478
 1479
 1480
 1481
 1482
 1483
 1484
 1485
 1486
 1487
 1488
 1489
 1490
 1491
 1492
 1493
 1494
 1495
 1496
 1497
 1498
 1499
 1500
 1501
 1502
 1503
 1504
 1505
 1506
 1507
 1508
 1509
 1510
 1511
 1512
 1513
 1514
 1515
 1516
 1517
 1518
 1519
 1520
 1521
 1522
 1523
 1524
 1525
 1526
 1527
 1528
 1529
 1530
 1531
 1532
 1533
 1534
 1535
 1536
 1537
 1538
 1539
 1540
 1541
 1542
 1543
 1544
 1545
 1546
 1547
 1548
 1549
 1550
 1551
 1552
 1553
 1554
 1555
 1556
 1557
 1558
 1559
 1560
 1561
 1562
 1563
 1564
 1565
 1566
 1567
 1568
 1569
 1570
 1571
 1572
 1573
 1574
 1575
 1576
 1577
 1578
 1579
 1580
 1581
 1582
 1583
 1584
 1585
 1586
 1587
 1588
 1589
 1590
 1591
 1592
 1593
 1594
 1595
 1596
 1597
 1598
 1599
 1600
 1601
 1602
 1603
 1604
 1605
 1606
 1607
 1608
 1609
 1610
 1611
 1612
 1613
 1614
 1615
 1616
 1617
 1618
 1619
 1620
 1621
 1622
 1623
 1624
 1625
 1626
 1627
 1628
 1629
 1630
 1631
 1632
 1633
 1634
 1635
 1636
 1637
 1638
 1639
 1640
 1641
 1642
 1643
 1644
 1645
 1646
 1647
 1648
 1649
 1650
 1651
 1652
 1653
 1654
 1655
 1656
 1657
 1658
 1659
 1660
 1661
 1662
 1663
 1664
 1665
 1666
 1667
 1668
 1669
 1670
 1671
 1672
 1673
 1674
 1675
 1676
 1677
 1678
 1679
 1680
 1681
 1682
 1683
 1684
 1685
 1686
 1687
 1688
 1689
 1690
 1691
 1692
 1693
 1694
 1695
 1696
 1697
 1698
 1699
 1700
 1701
 1702
 1703
 1704
 1705
 1706
 1707
 1708
 1709
 1710
 1711
 1712
 1713
 1714
 1715
 1716
 1717
 1718
 1719
 1720
 1721
 1722
 1723
 1724
 1725
 1726
 1727
 1728
 1729
 1730
 1731
 1732
 1733
 1734
 1735
 1736
 1737
 1738
 1739
 1740
 1741
 1742
 1743
 1744
 1745
 1746
 1747
 1748
 1749
 1750
 1751
 1752
 1753
 1754
 1755
 1756
 1757
 1758
 1759
 1760
 1761
 1762
 1763
 1764
 1765
 1766
 1767
 1768
 1769
 1770
 1771
 1772
 1773
 1774
 1775
 1776
 1777
 1778
 1779
 1780
 1781
 1782
 1783
 1784
 1785
 1786
 1787
 1788
 1789
 1790
 1791
 1792
 1793
 1794
 1795
 1796
 1797
 1798
 1799
 1800
 1801
 1802
 1803
 1804
 1805
 1806
 1807
 1808
 1809
 1810
 1811
 1812
 1813
 1814
 1815
 1816
 1817
 1818
 1819
 1820
 1821
 1822
 1823
 1824
 1825
 1826
 1827
 1828
 1829
 1830
 1831
 1832
 1833
 1834
 1835
 1836
 1837
 1838
 1839
 1840
 1841
 1842
 1843
 1844
 1845
 1846
 1847
 1848
 1849
 1850
 1851
 1852
 1853
 1854
 1855
 1856
 1857
 1858
 1859
 1860
 1861
 1862
 1863
 1864
 1865
 1866
 1867
 1868
 1869
 1870
 1871
 1872
 1873
 1874
 1875
 1876
 1877
 1878
 1879
 1880
 1881
 1882
 1883
 1884
 1885
 1886
 1887
 1888
 1889
 1890
 1891
 1892
 1893
 1894
 1895
 1896
 1897
 1898
 1899
 1900
 1901
 1902
 1903
 1904
 1905
 1906
 1907
 1908
 1909
 1910
 1911
 1912
 1913
 1914
 1915
 1916
 1917
 1918
 1919
 1920
 1921
 1922
 1923
 1924
 1925
 1926
 1927
 1928
 1929
 1930
 1931
 1932
 1933
 1934
 1935
 1936
 1937
 1938
 1939
 1940
 1941
 1942
 1943
 1944
 1945
 1946
 1947
 1948
 1949
 1950
 1951
 1952
 1953
 1954
 1955
 1956
 1957
 1958
 1959
 1960
 1961
 1962
 1963
 1964
 1965
 1966
 1967
 1968
 1969
 1970
 1971
 1972
 1973
 1974
 1975
 1976
 1977
 1978
 1979
 1980
 1981
 1982
 1983
 1984
 1985
 1986
 1987
 1988
 1989
 1990
 1991
 1992
 1993
 1994
 1995
 1996
 1997
 1998
 1999
 2000
 2001
 2002
 2003
 2004
 2005
 2006
 2007
 2008
 2009
 2010
 2011
 2012
 2013
 2014
 2015
 2016
 2017
 2018
 2019
 2020
 2021
 2022
 2023
 2024
 2025
 2026
 2027
 2028
 2029
 2030
 2031
 2032
 2033
 2034
 2035
 2036
 2037
 2038
 2039
 2040
 2041
 2042
 2043
 2044
 2045
 2046
 2047
 2048
 2049
 2050
 2051
 2052
 2053
 2054
 2055
 2056
 2057
 2058
 2059
 2060
 2061
 2062
 2063
 2064
 2065
 2066
 2067
 2068
 2069
 2070
 2071
 2072
 2073
 2074
 2075
 2076
 2077
 2078
 2079
 2080
 2081
 2082
 2083
 2084
 2085
 2086
 2087
 2088
 2089
 2090
 2091
 2092
 2093
 2094
 2095
 2096
 2097
 2098
 2099
 2100
 2101
 2102
 2103
 2104
 2105
 2106
 2107
 2108
 2109
 2110
 2111
 2112
 2113
 2114
 2115
 2116
 2117
 2118
 2119
 2120
 2121
 2122
 2123
 2124
 2125
 2126
 2127
 2128
 2129
 2130
 2131
 2132
 2133
 2134
 2135
 2136
 2137
 2138
 2139
 2140
 2141
 2142
 2143
 2144
 2145
 2146
 2147
 2148
 2149
 2150
 2151
 2152
 2153
 2154
 2155
 2156
 2157
 2158
 2159
 2160
 2161
 2162
 2163
 2164
 2165
 2166
 2167
 2168
 2169
 2170
 2171
 2172
 2173
 2174
 2175
 2176
 2177
 2178
 2179
 2180
 2181
 2182
 2183
 2184
 2185
 2186
 2187
 2188
 2189
 2190
 2191
 2192
 2193
 2194
 2195
 2196
 2197
 2198
 2199
 2200
 2201
 2202
 2203
 2204
 2205
 2206
 2207
 2208
 2209
 2210
 2211
 2212
 2213
 2214
 2215
 2216
 2217
 2218
 2219
 2220
 2221
 2222
 2223
 2224
 2225
 2226
 2227
 2228
 2229
 2230
 2231
 2232
 2233
 2234
 2235
 2236
 2237
 2238
 2239
 2240
 2241
 2242
 2243
 2244
 2245
 2246
 2247
 2248
 2249
 2250
 2251
 2252
 2253
 2254
 2255
 2256
 2257
 2258
 2259
 2260
 2261
 2262
 2263
 2264
 2265
 2266
 2267
 2268
 2269
 2270
 2271
 2272
 2273
 2274
 2275
 2276
 2277
 2278
 2279
 2280
 2281
 2282
 2283
 2284
 2285
 2286
 2287
 2288
 2289
 2290
 2291
 2292
 2293
 2294
 2295
 2296
 2297
 2298
 2299
 2300
 2301
 2302
 2303
 2304
 2305
 2306
 2307
 2308
 2309
 2310
 2311
 2312
 2313
 2314
 2315
 2316
 2317
 2318
 2319
 2320
 2321
 2322
 2323
 2324
 2325
 2326
 2327
 2328
 2329
 2330
 2331
 2332
 2333
 2334
 2335
 2336
 2337
 2338
 2339
 2340
 2341
 2342
 2343
 2344
 2345
 2346
 2347
 2348
 2349
 2350
 2351
 2352
 2353
 2354
 2355
 2356
 2357
 2358
 2359
 2360
 2361
 2362
 2363
 2364
 2365
 2366
 2367
 2368
 2369
 2370
 2371
 2372
 2373
 2374
 2375
 2376
 2377
 2378
 2379
 2380
 2381
 2382
 2383
 2384
 2385
 2386
 2387
 2388
 2389
 2390
 2391
 2392
 2393
 2394
 2395
 2396
 2397
 2398
 2399
 2400
 2401
 2402
 2403
 2404
 2405
 2406
 2407
 2408
 2409
 2410
 2411
 2412
 2413
 2414
 2415
 2416
 2417
 2418
 2419
 2420
 2421
 2422
 2423
 2424
 2425
 2426
 2427
 2428
 2429
 2430
 2431
 2432
 2433
 2434
 2435
 2436
 2437
 2438
 2439
 2440
 2441
 2442
 2443
 2444
 2445
 2446
 2447
 2448
 2449
 2450
 2451
 2452
 2453
 2454
 2455
 2456
 2457
 2458
 2459
 2460
 2461
 2462
 2463
 2464
 2465
 2466
 2467
 2468
 2469
 2470
 2471
 2472
 2473
 2474
 2475
 2476
 2477
 2478
 2479
 2480
 2481
 2482
 2483
 2484
 2485
 2486
 2487
 2488
 2489
 2490
 2491
 2492
 2493
 2494
 2495
 2496
 2497
 2498
 2499
 2500
 2501
 2502
 2503
 2504
 2505
 2506
 2507
 2508
 2509
 2510
 2511
 2512
 2513
 2514
 2515
 2516
 2517
 2518
 2519
 2520
 2521
 2522
 2523
 2524
 2525
 2526
 2527
 2528
 2529
 2530
 2531
 2532
 2533
 2534
 2535
 2536
 2537
 2538
 2539
 2540
 2541
 2542
 2543
 2544
 2545
 2546
 2547
 2548
 2549
 2550
 2551
 2552
 2553
 2554
 2555
 2556
 2557
 2558
 2559
 2560
 2561
 2562
 2563
 2564
 2565
 2566
 2567
 2568
 2569
 2570
 2571
 2572
 2573
 2574
 2575
 2576
 2577
 2578
 2579
 2580
 2581
 2582
 2583
 2584
 2585
 2586
 2587
 2588
 2589
 2590
 2591
 2592
 2593
 2594
 2595
 2596
 2597
 2598
 2599
 2600
 2601
 2602
 2603
 2604
 2605
 2606
 2607
 2608
 2609
 2610
 2611
 2612
 2613
 2614
 2615
 2616
 2617
 2618
 2619
 2620
 2621
 2622
 2623
 2624
 2625
 2626
 2627
 2628
 2629
 2630
 2631
 2632
 2633
 2634
 2635
 2636
 2637
 2638
 2639
 2640
 2641
 2642
 2643
 2644
 2645
 2646
 2647
 2648
 2649
 2650
 2651
 2652
 2653
 2654
 2655
 2656
 2657
 2658
 2659
 2660
 2661
 2662
 2663
 2664
 2665
 2666
 2667
 2668
 2669
 2670
 2671
 2672
 2673
 2674
 2675
 2676
 2677
 2678
 2679
 2680
 2681
 2682
 2683
 2684
 2685
 2686
 2687
 2688
 2689
 2690
 2691
 2692
 2693
 2694
 2695
 2696
 2697
 2698
 2699
 2700
 2701
 2702
 2703
 2704
 2705
 2706
 2707
 2708
 2709
 2710
 2711
 2712
 2713
 2714
 2715
 2716
 2717
 2718
 2719
 2720
 2721
 2722
 2723
 2724
 2725
 2726
 2727
 2728
 2729
 2730
 2731
 2732
 2733
 2734
 2735
 2736
 2737
 2738
 2739
 2740
 2741
 2742
 2743
 2744
 2745
 2746
 2747
 2748
 2749
 2750
 2751
 2752
 2753
 2754
 2755
 2756
 2757
 2758
 2759
 2760
 2761
 2762
 2763
 2764
 2765
 2766
 2767
 2768
 2769
 2770
 2771
 2772
 2773
 2774
 2775
 2776
 2777
 2778
 2779
 2780
 2781
 2782
 2783
 2784
 2785
 2786
 2787
 2788
 2789
 2790
 2791
 2792
 2793
 2794
 2795
 2796
 2797
 2798
 2799
 2800
 2801
 2802
 2803
 2804
 2805
 2806
 2807
 2808
 2809
 2810
 2811
 2812
 2813
 2814
 2815
 2816
 2817
 2818
 2819
 2820
 2821
 2822
 2823
 2824
 2825
 2826
 2827
 2828
 2829
 2830
 2831
 2832
 2833
 2834
 2835
 2836
 2837
 2838
 2839
 2840
 2841
 2842
 2843
 2844
 2845
 2846
 2847
 2848
 2849
 2850
 2851
 2852
 2853
 2854
 2855
 2856
 2857
 2858
 2859
 2860
 2861
 2862
 2863
 2864
 2865
 2866
 2867
 2868
 2869
 2870
 2871
 2872
 2873
 2874
 2875
 2876
 2877
 2878
 2879
 2880
 2881
 2882
 2883
 2884
 2885
 2886
 2887
 2888
 2889
 2890
 2891
 2892
 2893
 2894
 2895
 2896
 2897
 2898
 2899
 2900
 2901
 2902
 2903
 2904
 2905
 2906
 2907
 2908
 2909
 2910
 2911
 2912
 2913
 2914
 2915
 2916
 2917
 2918
 2919
 2920
 2921
 2922
 2923
 2924
 2925
 2926
 2927
 2928
 2929
 2930
 2931
 2932
 2933
 2934
 2935
 2936
 2937
 2938
 2939
 2940
 2941
 2942
 2943
 2944
 2945
 2946
 2947
 2948
 2949
 2950
 2951
 2952
 2953
 2954
 2955
 2956
 2957
 2958
 2959
 2960
 2961
 2962
 2963
 2964
 2965
 2966
 2967
 2968
 2969
 2970
 2971
 2972
 2973
 2974
 2975
 2976
 2977
 2978
 2979
 2980
 2981
 2982
 2983
 2984
 2985
 2986
 2987
 2988
 2989
 2990
 2991
 2992
 2993
 2994
 2995
 2996
 2997
 2998
 2999
 3000
 3001
 3002
 3003
 3004
 3005
 3006
 3007
 3008
 3009
 3010
 3011
 3012
 3013
 3014
 3015
 3016
 3017
 3018
 3019
 3020
 3021
 3022
 3023
 3024
 3025
 3026
 3027
 3028
 3029
 3030
 3031
 3032
 3033
 3034
 3035
 3036
 3037
 3038
 3039
 3040
 3041
 3042
 3043
 3044
 3045
 3046
 3047
 3048
 3049
 3050
 3051
 3052
 3053
 3054
 3055
 3056
 3057
 3058
 3059
 3060
 3061
 3062
 3063
 3064
 3065
 3066
 3067
 3068
 3069
 3070
 3071
 3072
 3073
 3074
 3075
 3076
 3077
 3078
 3079
 3080
 3081
 3082
 3083
 3084
 3085
 3086
 3087
 3088
 3089
 3090
 3091
 3092
 3093
 3094
 3095
 3096
 3097
 3098
 3099
 3100
 3101
 3102
 3103
 3104
 3105
 3106
 3107
 3108
 3109
 3110
 3111
 3112
 3113
 3114
 3115
 3116
 3117
 3118
 3119
 3120
 3121
 3122
 3123
 3124
 3125
 3126
 3127
 3128
 3129
 3130
 3131
 3132
 3133
 3134
 3135
 3136
 3137
 3138
 3139
 3140
 3141
 3142
 3143
 3144
 3145
 3146
 3147
 3148
 3149
 3150
 3151
 3152
 3153
 3154
 3155
 3156
 3157
 3158
 3159
 3160
 3161
 3162
 3163
 3164
 3165
 3166
 3167
 3168
 3169
 3170
 3171
 3172
 3173
 3174
 3175
 3176
 3177
 3178
 3179
 3180
 3181
 3182
 3183
 3184
 3185
 3186
 3187
 3188
 3189
 3190
 3191
 3192
 3193
 3194
 3195
 3196
 3197
 3198
 3199
 3200
 3201
 3202
 3203
 3204
 3205
 3206
 3207
 3208
 3209
 3210
 3211
 3212
 3213
 3214
 3215
 3216
 3217
 3218
 3219
 3220
 3221
 3222
 3223
 3224
 3225
 3226
 3227
 3228
 3229
 3230
 3231
 3232
 3233
 3234
 3235
 3236
 3237
 3238
 3239
 3240
 3241
 3242
 3243
 3244
 3245
 3246
 3247
 3248
 3249
 3250
 3251
 3252
 3253
 3254
 3255
 3256
 3257
 3258
 3259
 3260
 3261
 3262
 3263
 3264
 3265
 3266
 3267
 3268
 3269
 3270
 3271
 3272
 3273
 3274
 3275
 3276
 3277
 3278
 3279
 3280
 3281
 3282
 3283
 3284
 3285
 3286
 3287
 3288
 3289
 3290
 3291
 3292
 3293
 3294
 3295
 3296
 3297
 3298
 3299
 3300
 3301
 3302
 3303
 3304
 3305
 3306
 3307
 3308
 3309
 3310
 3311
 3312
 3313
 3314
 3315
 3316
 3317
 3318
 3319
 3320
 3321
 3322
 3323
 3324
 3325
 3326
 3327
 3328
 3329
 3330
 3331
 3332
 3333
 3334
 3335
 3336
 3337
 3338
 3339
 3340
 3341
 3342
 3343
 3344
 3345
 3346
 3347
 3348
 3349
 3350
 3351
 3352
 3353
 3354
 3355
 3356
 3357
 3358
 3359
 3360
 3361
 3362
 3363
 3364
 3365
 3366
 3367
 3368
 3369
 3370
 3371
 3372
 3373
 3374
 3375
 3376
 3377
 3378
 3379
 3380
 3381
 3382
 3383
 3384
 3385
 3386
 3387
 3388
 3389
 3390
 3391
 3392
 3393
 3394
 3395
 3396
 3397
 3398
 3399
 3400
 3401
 3402
 3403
 3404
 3405
 3406
 3407
 3408
 3409
 3410
 3411
 3412
 3413
 3414
 3415
 3416
 3417
 3418
 3419
 3420
 3421
 3422
 3423
 3424
 3425
 3426
 3427
 3428
 3429
 3430
 3431
 3432
 3433
 3434
 3435
 3436
 3437
 3438
 3439
 3440
 3441
 3442
 3443
 3444
 3445
 3446
 3447
 3448
 3449
 3450
 3451
 3452
 3453
 3454
 3455
 3456
 3457
 3458
 3459
 3460
 3461
 3462
 3463
 3464
 3465
 3466
 3467
 3468
 3469
 3470
 3471
 3472
 3473
 3474
 3475
 3476
 3477
 3478
 3479
 3480
 3481
 3482
 3483
 3484
 3485
 3486
 3487
 3488
 3489
 3490
 3491
 3492
 3493
 3494
 3495
 3496
 3497
 3498
 3499
 3500
 3501
 3502
 3503
 3504
 3505
 3506
 3507
 3508
 3509
 3510
 3511
 3512
 3513
 3514
 3515
 3516
 3517
 3518
 3519
 3520
 3521
 3522
 3523
 3524
 3525
 3526
 3527
 3528
 3529
 3530
 3531
 3532
 3533
 3534
 3535
 3536
 3537
 3538
 3539
 3540
 3541
 3542
 3543
 3544
 3545
 3546
 3547
 3548
 3549
 3550
 3551
 3552
 3553
 3554
 3555
 3556
 3557
 3558
 3559
 3560
 3561
 3562
 3563
 3564
 3565
 3566
 3567
 3568
 3569
 3570
 3571
 3572
 3573
 3574
 3575
 3576
 3577
 3578
 3579
 3580
 3581
 3582
 3583
 3584
 3585
 3586
 3587
 3588
 3589
 3590
 3591
 3592
 3593
 3594
 3595
 3596
 3597
 3598
 3599
 3600
 3601
 3602
 3603
 3604
 3605
 3606
 3607
 3608
 3609
 3610
 3611
 3612
 3613
 3614
 3615
 3616
 3617
 3618
 3619
 3620
 3621
 3622
 3623
 3624
 3625
 3626
 3627
 3628
 3629
 3630
 3631
 3632
 3633
 3634
 3635
 3636
 3637
 3638
 3639
 3640
 3641
 3642
 3643
 3644
 3645
 3646
 3647
 3648
 3649
 3650
 3651
 3652
 3653
 3654
 3655
 3656
 3657
 3658
 3659
 3660
 3661
 3662
 3663
 3664
 3665
 3666
 3667
 3668
 3669
 3670
 3671
 3672
 3673
 3674
 3675
 3676
 3677
 3678
 3679
 3680
 3681
 3682
 3683
 3684
 3685
 3686
 3687
 3688
 3689
 3690
 3691
 3692
 3693
 3694
 3695
 3696
 3697
 3698
 3699
 3700
 3701
 3702
 3703
 3704
 3705
 3706
 3707
 3708
 3709
 3710
 3711
 3712
 3713
 3714
 3715
 3716
 3717
 3718
 3719
 3720
 3721
 3722
 3723
 3724
 3725
 3726
 3727
 3728
 3729
 3730
 3731
 3732
 3733
 3734
 3735
 3736
 3737
 3738
 3739
 3740
 3741
 3742
 3743
 3744
 3745
 3746
 3747
 3748
 3749
 3750
 3751
 3752
 3753
 3754
 3755
 3756
 3757
 3758
 3759
 3760
 3761
 3762
 3763
 3764
 3765
 3766
 3767
 3768
 3769
 3770
 3771
 3772
 3773
 3774
 3775
 3776
 3777
 3778
 3779
 3780
 3781
 3782
 3783
 3784
 3785
 3786
 3787
 3788
 3789
 3790
 3791
 3792
 3793
 3794
 3795
 3796
 3797
 3798
 3799
 3800
 3801
 3802
 3803
 3804
 3805
 3806
 3807
 3808
 3809
 3810
 3811
 3812
 3813
 3814
 3815
 3816
 3817
 3818
 3819
 3820
 3821
 3822
 3823
 3824
 3825
 3826
 3827
 3828
 3829
 3830
 3831
 3832
 3833
 3834
 3835
 3836
 3837
 3838
 3839
 3840
 3841
 3842
 3843
 3844
 3845
 3846
 3847
 3848
 3849
 3850
 3851
 3852
 3853
 3854
 3855
 3856
 3857
 3858
 3859
 3860
 3861
 3862
 3863
 3864
 3865
 3866
 3867
 3868
 3869
 3870
 3871
 3872
 3873
 3874
 3875
 3876
 3877
 3878
 3879
 3880
 3881
 3882
 3883
 3884
 3885
 3886
 3887
 3888
 3889
 3890
 3891
 3892
 3893
 3894
 3895
 3896
 3897
 3898
 3899
 3900
 3901
 3902
 3903
 3904
 3905
 3906
 3907
 3908
 3909
 3910
 3911
 3912
 3913
 3914
 3915
 3916
 3917
 3918
 3919
 3920
 3921
 3922
 3923
 3924
 3925
 3926
 3927
 3928
 3929
 3930
 3931
 3932
 3933
 3934
 3935
 3936
 3937
 3938
 3939
 3940
 3941
 3942
 3943
 3944
 3945
 3946
 3947
 3948
 3949
 3950
 3951
 3952
 3953
 3954
 3955
 3956
 3957
 3958
 3959
 3960
 3961
 3962
 3963
 3964
 3965
 3966
 3967
 3968
 3969
 3970
 3971
 3972
 3973
 3974
 3975
 3976
 3977
 3978
 3979
 3980
 3981
 3982
 3983
 3984
 3985
 3986
 3987
 3988
 3989
 3990
 3991
 3992
 3993
 3994
 3995
 3996
 3997
 3998
 3999
 4000
 4001
 4002
 4003
 4004
 4005
 4006
 4007
 4008
 4009
 4010
 4011
 4012
 4013
 4014
 4015
 4016
 4017
 4018
 4019
 4020
 4021
 4022
 4023
 4024
 4025
 4026
 4027
 4028
 4029
 4030
 4031
 4032
 4033
 4034
 4035
 4036
 4037
 4038
 4039
 4040
 4041
 4042
 4043
 4044
 4045
 4046
 4047
 4048
 4049
 4050
 4051
 4052
 4053
 4054
 4055
 4056
 4057
 4058
 4059
 4060
 4061
 4062
 4063
 4064
 4065
 4066
 4067
 4068
 4069
 4070
 4071
 4072
 4073
 4074
 4075
 4076
 4077
 4078
 4079
 4080
 4081
 4082
 4083
 4084
 4085
 4086
 4087
 4088
 4089
 4090
 4091
 4092
 4093
 4094
 4095
 4096
 4097
 4098
 4099
 4100
 4101
 4102
 4103
 4104
 4105
 4106
 4107
 4108
 4109
 4110
 4111
 4112
 4113
 4114
 4115
 4116
 4117
 4118
 4119
 4120
 4121
 4122
 4123
 4124
 4125
 4126
 4127
 4128
 4129
 4130
 4131
 4132
 4133
 4134
 4135
 4136
 4137
 4138
 4139
 4140
 4141
 4142
 4143
 4144
 4145
 4146
 4147
 4148
 4149
 4150
 4151
 4152
 4153
 4154
 4155
 4156
 4157
 4158
 4159
 4160
 4161
 4162
 4163
 4164
 4165
 4166
 4167
 4168
 4169
 4170
 4171
 4172
 4173
 4174
 4175
 4176
 4177
 4178
 4179
 4180
 4181
 4182
 4183
 4184
 4185
 4186
 4187
 4188
 4189
 4190
 4191
 4192
 4193
 4194
 4195
 4196
 4197
 4198
 4199
 4200
 4201
 4202
 4203
 4204
 4205
 4206
 4207
 4208
 4209
 4210
 4211
 4212
 4213
 4214
 4215
 4216
 4217
 4218
 4219
 4220
 4221
 4222
 4223
 4224
 4225
 4226
 4227
 4228
 4229
 4230
 4231
 4232
 4233
 4234
 4235
 4236
 4237
 4238
 4239
 4240
 4241
 4242
 4243
 4244
 4245
 4246
 4247
 4248
 4249
 4250
 4251
 4252
 4253
 4254
 4255
 4256
 4257
 4258
 4259
 4260
 4261
 4262
 4263
 4264
 4265
 4266
 4267
 4268
 4269
 4270
 4271
 4272
 4273
 4274
 4275
 4276
 4277
 4278
 4279
 4280
 4281
 4282
 4283
 4284
 4285
 4286
 4287
 4288
 4289
 4290
 4291
 4292
 4293
 4294
 4295
 4296
 4297
 4298
 4299
 4300
 4301
 4302
 4303
 4304
 4305
 4306
 4307
 4308
 4309
 4310
 4311
 4312
 4313
 4314
 4315
 4316
 4317
 4318
 4319
 4320
 4321
 4322
 4323
 4324
 4325
 4326
 4327
 4328
 4329
 4330
 4331
 4332
 4333
 4334
 4335
 4336
 4337
 4338
 4339
 4340
 4341
 4342
 4343
 4344
 4345
 4346
 4347
 4348
 4349
 4350
 4351
 4352
 4353
 4354
 4355
 4356
 4357
 4358
 4359
 4360
 4361
 4362
 4363
 4364
 4365
 4366
 4367
 4368
 4369
 4370
 4371
 4372
 4373
 4374
 4375
 4376
 4377
 4378
 4379
 4380
 4381
 4382
 4383
 4384
 4385
 4386
 4387
 4388
 4389
 4390
 4391
 4392
 4393
 4394
 4395
 4396
 4397
 4398
 4399
 4400
 4401
 4402
 4403
 4404
 4405
 4406
 4407
 4408
 4409
 4410
 4411
 4412
 4413
 4414
 4415
 4416
 4417
 4418
 4419
 4420
 4421
 4422
 4423
 4424
 4425
 4426
 4427
 4428
 4429
 4430
 4431
 4432
 4433
 4434
 4435
 4436
 4437
 4438
 4439
 4440
 4441
 4442
 4443
 4444
 4445
 4446
 4447
 4448
 4449
 4450
 4451
 4452
 4453
 4454
 4455
 4456
 4457
 4458
 4459
 4460
 4461
 4462
 4463
 4464
 4465
 4466
 4467
 4468
 4469
 4470
 4471
 4472
 4473
 4474
 4475
 4476
 4477
 4478
 4479
 4480
 4481
 4482
 4483
 4484
 4485
 4486
 4487
 4488
 4489
 4490
 4491
 4492
 4493
 4494
 4495
 4496
 4497
 4498
 4499
 4500
 4501
 4502
 4503
 4504
 4505
 4506
 4507
 4508
 4509
 4510
 4511
 4512
 4513
 4514
 4515
 4516
 4517
 4518
 4519
 4520
 4521
 4522
 4523
 4524
 4525
 4526
 4527
 4528
 4529
 4530
 4531
 4532
 4533
 4534
 4535
 4536
 4537
 4538
 4539
 4540
 4541
 4542
 4543
 4544
 4545
 4546
 4547
 4548
 4549
 4550
 4551
 4552
 4553
 4554
 4555
 4556
 4557
 4558
 4559
 4560
 4561
 4562
 4563
 4564
 4565
 4566
 4567
 4568
 4569
 4570
 4571
 4572
 4573
 4574
 4575
 4576
 4577
 4578
 4579
 4580
 4581
 4582
 4583
 4584
 4585
 4586
 4587
 4588
 4589
 4590
 4591
 4592
 4593
 4594
 4595
 4596
 4597
 4598
 4599
 4600
 4601
 4602
 4603
 4604
 4605
 4606
 4607
 4608
 4609
 4610
 4611
 4612
 4613
 4614
 4615
 4616
 4617
 4618
 4619
 4620
 4621
 4622
 4623
 4624
 4625
 4626
 4627
 4628
 4629
 4630
 4631
 4632
 4633
 4634
 4635
 4636
 4637
 4638
 4639
 4640
 4641
 4642
 4643
 4644
 4645
 4646
 4647
 4648
 4649
 4650
 4651
 4652
 4653
 4654
 4655
 4656
 4657
 4658
 4659
 4660
 4661
 4662
 4663
 4664
 4665
 4666
 4667
 4668
 4669
 4670
 4671
 4672
 4673
 4674
 4675
 4676
 4677
 4678
 4679
 4680
 4681
 4682
 4683
 4684
 4685
 4686
 4687
 4688
 4689
 4690
 4691
 4692
 4693
 4694
 4695
 4696
 4697
 4698
 4699
 4700
 4701
 4702
 4703
 4704
 4705
 4706
 4707
 4708
 4709
 4710
 4711
 4712
 4713
 4714
 4715
 4716
 4717
 4718
 4719
 4720
 4721
 4722
 4723
 4724
 4725
 4726
 4727
 4728
 4729
 4730
 4731
 4732
 4733
 4734
 4735
 4736
 4737
 4738
 4739
 4740
 4741
 4742
 4743
 4744
 4745
 4746
 4747
 4748
 4749
 4750
 4751
 4752
 4753
 4754
 4755
 4756
 4757
 4758
 4759
 4760
 4761
 4762
 4763
 4764
 4765
 4766
 4767
 4768
 4769
 4770
 4771
 4772
 4773
 4774
 4775
 4776
 4777
 4778
 4779
 4780
 4781
 4782
 4783
 4784
 4785
 4786
 4787
 4788
 4789
 4790
 4791
 4792
 4793
 4794
 4795
 4796
 4797
 4798
 4799
 4800
 4801
 4802
 4803
 4804
 4805
 4806
 4807
 4808
 4809
 4810
 4811
 4812
 4813
 4814
 4815
 4816
 4817
 4818
 4819
 4820
 4821
 4822
 4823
 4824
 4825
 4826
 4827
 4828
 4829
 4830
 4831
 4832
 4833
 4834
 4835
 4836
 4837
 4838
 4839
 4840
 4841
 4842
 4843
 4844
 4845
 4846
 4847
 4848
 4849
 4850
 4851
 4852
 4853
 4854
 4855
 4856
 4857
 4858
 4859
 4860
 4861
 4862
 4863
 4864
 4865
 4866
 4867
 4868
 4869
 4870
 4871
 4872
 4873
 4874
 4875
 4876
 4877
 4878
 4879
 4880
 4881
 4882
 4883
 4884
 4885
 4886
 4887
 4888
 4889
 4890
 4891
 4892
 4893
 4894
 4895
 4896
 4897
 4898
 4899
 4900
 4901
 4902
 4903
 4904
 4905
 4906
 4907
 4908
 4909
 4910
 4911
 4912
 4913
 4914
 4915
 4916
 4917
 4918
 4919
 4920
 4921
 4922
 4923
 4924
 4925
 4926
 4927
 4928
 4929
 4930
 4931
 4932
 4933
 4934
 4935
 4936
 4937
 4938
 4939
 4940
 4941
 4942
 4943
 4944
 4945
 4946
 4947
 4948
 4949
 4950
 4951
 4952
 4953
 4954
 4955
 4956
 4957
 4958
 4959
 4960
 4961
 4962
 4963
 4964
 4965
 4966
 4967
 4968
 4969
 4970
 4971
 4972
 4973
 4974
 4975
 4976
 4977
 4978
 4979
 4980
 4981
 4982
 4983
 4984
 4985
 4986
 4987
 4988
 4989
 4990
 4991
 4992
 4993
 4994
 4995
 4996
 4997
 4998
 4999
 5000
 5001
 5002
 5003
 5004
 5005
 5006
 5007
 5008
 5009
 5010
 5011
 5012
 5013
 5014
 5015
 5016
 5017
 5018
 5019
 5020
 5021
 5022
 5023
 5024
 5025
 5026
 5027
 5028
 5029
 5030
 5031
 5032
 5033
 5034
 5035
 5036
 5037
 5038
 5039
 5040
 5041
 5042
 5043
 5044
 5045
 5046
 5047
 5048
 5049
 5050
 5051
 5052
 5053
 5054
 5055
 5056
 5057
 5058
 5059
 5060
 5061
 5062
 5063
 5064
 5065
 5066
 5067
 5068
 5069
 5070
 5071
 5072
 5073
 5074
 5075
 5076
 5077
 5078
 5079
 5080
 5081
 5082
 5083
 5084
 5085
 5086
 5087
 5088
 5089
 5090
 5091
 5092
 5093
 5094
 5095
 5096
 5097
 5098
 5099
 5100
 5101
 5102
 5103
 5104
 5105
 5106
 5107
 5108
 5109
 5110
 5111
 5112
 5113
 5114
 5115
 5116
 5117
 5118
 5119
 5120
 5121
 5122
 5123
 5124
 5125
 5126
 5127
 5128
 5129
 5130
 5131
 5132
 5133
 5134
 5135
 5136
 5137
 5138
 5139
 5140
 5141
 5142
 5143
 5144
 5145
 5146
 5147
 5148
 5149
 5150
 5151
 5152
 5153
 5154
 5155
 5156
 5157
 5158
 5159
 5160
 5161
 5162
 5163
 5164
 5165
 5166
 5167
 5168
 5169
 5170
 5171
 5172
 5173
 5174
 5175
 5176
 5177
 5178
 5179
 5180
 5181
 5182
 5183
 5184
 5185
 5186
 5187
 5188
 5189
 5190
 5191
 5192
 5193
 5194
 5195
 5196
 5197
 5198
 5199
 5200
 5201
 5202
 5203
 5204
 5205
 5206
 5207
 5208
 5209
 5210
 5211
 5212
 5213
 5214
 5215
 5216
 5217
 5218
 5219
 5220
 5221
 5222
 5223
 5224
 5225
 5226
 5227
 5228
 5229
 5230
 5231
 5232
 5233
 5234
 5235
 5236
 5237
 5238
 5239
 5240
 5241
 5242
 5243
 5244
 5245
 5246
 5247
 5248
 5249
 5250
 5251
 5252
 5253
 5254
 5255
 5256
 5257
 5258
 5259
 5260
 5261
 5262
 5263
 5264
 5265
 5266
 5267
 5268
 5269
 5270
 5271
 5272
 5273
 5274
 5275
 5276
 5277
 5278
 5279
 5280
 5281
 5282
 5283
 5284
 5285
 5286
 5287
 5288
 5289
 5290
 5291
 5292
 5293
 5294
 5295
 5296
 5297
 5298
 5299
 5300
 5301
 5302
 5303
 5304
 5305
 5306
 5307
 5308
 5309
 5310
 5311
 5312
 5313
 5314
 5315
 5316
 5317
 5318
 5319
 5320
 5321
 5322
 5323
 5324
 5325
 5326
 5327
 5328
 5329
 5330
 5331
 5332
 5333
 5334
 5335
 5336
 5337
 5338
 5339
 5340
 5341
 5342
 5343
 5344
 5345
 5346
 5347
 5348
 5349
 5350
 5351
 5352
 5353
 5354
 5355
 5356
 5357
 5358
 5359
 5360
 5361
 5362
 5363
 5364
 5365
 5366
 5367
 5368
 5369
 5370
 5371
 5372
 5373
 5374
 5375
 5376
 5377
 5378
 5379
 5380
 5381
 5382
 5383
 5384
 5385
 5386
 5387
 5388
 5389
 5390
 5391
 5392
 5393
 5394
 5395
 5396
 5397
 5398
 5399
 5400
 5401
 5402
 5403
 5404
 5405
 5406
 5407
 5408
 5409
 5410
 5411
 5412
 5413
 5414
 5415
 5416
 5417
 5418
 5419
 5420
 5421
 5422
 5423
 5424
 5425
 5426
 5427
 5428
 5429
 5430
 5431
 5432
 5433
 5434
 5435
 5436
 5437
 5438
 5439
 5440
 5441
 5442
 5443
 5444
 5445
 5446
 5447
 5448
 5449
 5450
 5451
 5452
 5453
 5454
 5455
 5456
 5457
 5458
 5459
 5460
 5461
 5462
 5463
 5464
 5465
 5466
 5467
 5468
 5469
 5470
 5471
 5472
 5473
 5474
 5475
 5476
 5477
 5478
 5479
 5480
 5481
 5482
 5483
 5484
 5485
 5486
 5487
 5488
 5489
 5490
 5491
 5492
 5493
 5494
 5495
 5496
 5497
 5498
 5499
 5500
 5501
 5502
 5503
 5504
 5505
 5506
 5507
 5508
 5509
 5510
 5511
 5512
 5513
 5514
 5515
 5516
 5517
 5518
 5519
 5520
 5521
 5522
 5523
 5524
 5525
 5526
 5527
 5528
 5529
 5530
 5531
 5532
 5533
 5534
 5535
 5536
 5537
 5538
 5539
 5540
 5541
 5542
 5543
 5544
 5545
 5546
 5547
 5548
 5549
 5550
 5551
 5552
 5553
 5554
 5555
 5556
 5557
 5558
 5559
 5560
 5561
 5562
 5563
 5564
 5565
 5566
 5567
 5568
 5569
 5570
 5571
 5572
 5573
 5574
 5575
 5576
 5577
 5578
 5579
 5580
 5581
 5582
 5583
 5584
 5585
 5586
 5587
 5588
 5589
 5590
 5591
 5592
 5593
 5594
 5595
 5596
 5597
 5598
 5599
 5600
 5601
 5602
 5603
 5604
 5605
 5606
 5607
 5608
 5609
 5610
 5611
 5612
 5613
 5614
 5615
 5616
 5617
 5618
 5619
 5620
 5621
 5622
 5623
 5624
 5625
 5626
 5627
 5628
 5629
 5630
 5631
 5632
 5633
 5634
 5635
 5636
 5637
 5638
 5639
 5640
 5641
 5642
 5643
 5644
 5645
 5646
 5647
 5648
 5649
 5650
 5651
 5652
 5653
 5654
 5655
 5656
 5657
 5658
 5659
 5660
 5661
 5662
 5663
 5664
 5665
 5666
 5667
 5668
 5669
 5670
 5671
 5672
 5673
 5674
 5675
 5676
 5677
 5678
 5679
 5680
 5681
 5682
 5683
 5684
 5685
 5686
 5687
 5688
 5689
 5690
 5691
 5692
 5693
 5694
 5695
 5696
 5697
 5698
 5699
 5700
 5701
 5702
 5703
 5704
 5705
 5706
 5707
 5708
 5709
 5710
 5711
 5712
 5713
 5714
 5715
 5716
 5717
 5718
 5719
 5720
 5721
 5722
 5723
 5724
 5725
 5726
 5727
 5728
 5729
 5730
 5731
 5732
 5733
 5734
 5735
 5736
 5737
 5738
 5739
 5740
 5741
 5742
 5743
 5744
 5745
 5746
 5747
 5748
 5749
 5750
 5751
 5752
 5753
 5754
 5755
 5756
 5757
 5758
 5759
 5760
 5761
 5762
 5763
 5764
 5765
 5766
 5767
 5768
 5769
 5770
 5771
 5772
 5773
 5774
 5775
 5776
 5777
 5778
 5779
 5780
 5781
 5782
 5783
 5784
 5785
 5786
 5787
 5788
 5789
 5790
 5791
 5792
 5793
 5794
 5795
 5796
 5797
 5798
 5799
 5800
 5801
 5802
 5803
 5804
 5805
 5806
 5807
 5808
 5809
 5810
 5811
 5812
 5813
 5814
 5815
 5816
 5817
 5818
 5819
 5820
 5821
 5822
 5823
 5824
 5825
 5826
 5827
 5828
 5829
 5830
 5831
 5832
 5833
 5834
 5835
 5836
 5837
 5838
 5839
 5840
 5841
 5842
 5843
 5844
 5845
 5846
 5847
 5848
 5849
 5850
 5851
 5852
 5853
 5854
 5855
 5856
 5857
 5858
 5859
 5860
 5861
 5862
 5863
 5864
 5865
 5866
 5867
 5868
 5869
 5870
 5871
 5872
 5873
 5874
 5875
 5876
 5877
 5878
 5879
 5880
 5881
 5882
 5883
 5884
 5885
 5886
 5887
 5888
 5889
 5890
 5891
 5892
 5893
 5894
 5895
 5896
 5897
 5898
 5899
 5900
 5901
 5902
 5903
 5904
 5905
 5906
 5907
 5908
 5909
 5910
 5911
 5912
 5913
 5914
 5915
 5916
 5917
 5918
 5919
 5920
 5921
 5922
 5923
 5924
 5925
 5926
 5927
 5928
 5929
 5930
 5931
 5932
 5933
 5934
 5935
 5936
 5937
 5938
 5939
 5940
 5941
 5942
 5943
 5944
 5945
 5946
 5947
 5948
 5949
 5950
 5951
 5952
 5953
 5954
 5955
 5956
 5957
 5958
 5959
 5960
 5961
 5962
 5963
 5964
 5965
 5966
 5967
 5968
 5969
 5970
 5971
 5972
 5973
 5974
 5975
 5976
 5977
 5978
 5979
 5980
 5981
 5982
 5983
 5984
 5985
 5986
 5987
 5988
 5989
 5990
 5991
 5992
 5993
 5994
 5995
 5996
 5997
 5998
 5999
 6000
 6001
 6002
 6003
 6004
 6005
 6006
 6007
 6008
 6009
 6010
 6011
 6012
 6013
 6014
 6015
 6016
 6017
 6018
 6019
 6020
 6021
 6022
 6023
 6024
 6025
 6026
 6027
 6028
 6029
 6030
 6031
 6032
 6033
 6034
 6035
 6036
 6037
 6038
 6039
 6040
 6041
 6042
 6043
 6044
 6045
 6046
 6047
 6048
 6049
 6050
 6051
 6052
 6053
 6054
 6055
 6056
 6057
 6058
 6059
 6060
 6061
 6062
 6063
 6064
 6065
 6066
 6067
 6068
 6069
 6070
 6071
 6072
 6073
 6074
 6075
 6076
 6077
 6078
 6079
 6080
 6081
 6082
 6083
 6084
 6085
 6086
 6087
 6088
 6089
 6090
 6091
 6092
 6093
 6094
 6095
 6096
 6097
 6098
 6099
 6100
 6101
 6102
 6103
 6104
 6105
 6106
 6107
 6108
 6109
 6110
 6111
 6112
 6113
 6114
 6115
 6116
 6117
 6118
 6119
 6120
 6121
 6122
 6123
 6124
 6125
 6126
 6127
 6128
 6129
 6130
 6131
 6132
 6133
 6134
 6135
 6136
 6137
 6138
 6139
 6140
 6141
 6142
 6143
 6144
 6145
 6146
 6147
 6148
 6149
 6150
 6151
 6152
 6153
 6154
 6155
 6156
 6157
 6158
 6159
 6160
 6161
 6162
 6163
 6164
 6165
 6166
 6167
 6168
 6169
 6170
 6171
 6172
 6173
 6174
 6175
 6176
 6177
 6178
 6179
 6180
 6181
 6182
 6183
 6184
 6185
 6186
 6187
 6188
 6189
 6190
 6191
 6192
 6193
 6194
 6195
 6196
 6197
 6198
 6199
 6200
 6201
 6202
 6203
 6204
 6205
 6206
 6207
 6208
 6209
 6210
 6211
 6212
 6213
 6214
 6215
 6216
 6217
 6218
 6219
 6220
 6221
 6222
 6223
 6224
 6225
 6226
 6227
 6228
 6229
 6230
 6231
 6232
 6233
 6234
 6235
 6236
 6237
 6238
 6239
 6240
 6241
 6242
 6243
 6244
 6245
 6246
 6247
 6248
 6249
 6250
 6251
 6252
 6253
 6254
 6255
 6256
 6257
 6258
 6259
 6260
 6261
 6262
 6263
 6264
 6265
 6266
 6267
 6268
 6269
 6270
 6271
 6272
 6273
 6274
 6275
 6276
 6277
 6278
 6279
 6280
 6281
 6282
 6283
 6284
 6285
 6286
 6287
 6288
 6289
 6290
 6291
 6292
 6293
 6294
 6295
 6296
 6297
 6298
 6299
 6300
 6301
 6302
 6303
 6304
 6305
 6306
 6307
 6308
 6309
 6310
 6311
 6312
 6313
 6314
 6315
 6316
 6317
 6318
 6319
 6320
 6321
 6322
 6323
 6324
 6325
 6326
 6327
 6328
 6329
 6330
 6331
 6332
 6333
 6334
 6335
 6336
 6337
 6338
 6339
 6340
 6341
 6342
 6343
 6344
 6345
 6346
 6347
 6348
 6349
 6350
 6351
 6352
 6353
 6354
 6355
 6356
 6357
 6358
 6359
 6360
 6361
 6362
 6363
 6364
 6365
 6366
 6367
 6368
 6369
 6370
 6371
 6372
 6373
 6374
 6375
 6376
 6377
 6378
 6379
 6380
 6381
 6382
 6383
 6384
 6385
 6386
 6387
 6388
 6389
 6390
 6391
 6392
 6393
 6394
 6395
 6396
 6397
 6398
 6399
 6400
 6401
 6402
 6403
 6404
 6405
 6406
 6407
 6408
 6409
 6410
 6411
 6412
 6413
 6414
 6415
 6416
 6417
 6418
 6419
 6420
 6421
 6422
 6423
 6424
 6425
 6426
 6427
 6428
 6429
 6430
 6431
 6432
 6433
 6434
 6435
 6436
 6437
 6438
 6439
 6440
 6441
 6442
 6443
 6444
 6445
 6446
 6447
 6448
 6449
 6450
 6451
 6452
 6453
 6454
 6455
 6456
 6457
 6458
 6459
 6460
 6461
 6462
 6463
 6464
 6465
 6466
 6467
 6468
 6469
 6470
 6471
 6472
 6473
 6474
 6475
 6476
 6477
 6478
 6479
 6480
 6481
 6482
 6483
 6484
 6485
 6486
 6487
 6488
 6489
 6490
 6491
 6492
 6493
 6494
 6495
 6496
 6497
 6498
 6499
 6500
 6501
 6502
 6503
 6504
 6505
 6506
 6507
 6508
 6509
 6510
 6511
 6512
 6513
 6514
 6515
 6516
 6517
 6518
 6519
 6520
 6521
 6522
 6523
 6524
 6525
 6526
 6527
 6528
 6529
 6530
 6531
 6532
 6533
 6534
 6535
 6536
 6537
 6538
 6539
 6540
 6541
 6542
 6543
 6544
 6545
 6546
 6547
 6548
 6549
 6550
 6551
 6552
 6553
 6554
 6555
 6556
 6557
 6558
 6559
 6560
 6561
 6562
 6563
 6564
 6565
 6566
 6567
 6568
 6569
 6570
 6571
 6572
 6573
 6574
 6575
 6576
 6577
 6578
 6579
 6580
 6581
 6582
 6583
 6584
 6585
 6586
 6587
 6588
 6589
 6590
 6591
 6592
 6593
 6594
 6595
 6596
 6597
 6598
 6599
 6600
 6601
 6602
 6603
 6604
 6605
 6606
 6607
 6608
 6609
 6610
 6611
 6612
 6613
 6614
 6615
 6616
 6617
 6618
 6619
 6620
 6621
 6622
 6623
 6624
 6625
 6626
 6627
 6628
 6629
 6630
 6631
 6632
 6633
 6634
 6635
 6636
 6637
 6638
 6639
 6640
 6641
 6642
 6643
 6644
 6645
 6646
 6647
 6648
 6649
 6650
 6651
 6652
 6653
 6654
 6655
 6656
 6657
 6658
 6659
 6660
 6661
 6662
 6663
 6664
 6665
 6666
 6667
 6668
 6669
 6670
 6671
 6672
 6673
 6674
 6675
 6676
 6677
 6678
 6679
 6680
 6681
 6682
 6683
 6684
 6685
 6686
 6687
 6688
 6689
 6690
 6691
 6692
 6693
 6694
 6695
 6696
 6697
 6698
 6699
 6700
 6701
 6702
 6703
 6704
 6705
 6706
 6707
 6708
 6709
 6710
 6711
 6712
 6713
 6714
 6715
 6716
 6717
 6718
 6719
 6720
 6721
 6722
 6723
 6724
 6725
 6726
 6727
 6728
 6729
 6730
 6731
 6732
 6733
 6734
 6735
 6736
 6737
 6738
 6739
 6740
 6741
 6742
 6743
 6744
 6745
 6746
 6747
 6748
 6749
 6750
 6751
 6752
 6753
 6754
 6755
 6756
 6757
 6758
 6759
 6760
 6761
 6762
 6763
 6764
 6765
 6766
 6767
 6768
 6769
 6770
 6771
 6772
 6773
 6774
 6775
 6776
 6777
 6778
 6779
 6780
 6781
 6782
 6783
 6784
 6785
 6786
 6787
 6788
 6789
 6790
 6791
 6792
 6793
 6794
 6795
 6796
 6797
 6798
 6799
 6800
 6801
 6802
 6803
 6804
 6805
 6806
 6807
 6808
 6809
 6810
 6811
 6812
 6813
 6814
 6815
 6816
 6817
 6818
 6819
 6820
 6821
 6822
 6823
 6824
 6825
 6826
 6827
 6828
 6829
 6830
 6831
 6832
 6833
 6834
 6835
 6836
 6837
 6838
 6839
 6840
 6841
 6842
 6843
 6844
 6845
 6846
 6847
 6848
 6849
 6850
 6851
 6852
 6853
 6854
 6855
 6856
 6857
 6858
 6859
 6860
 6861
 6862
 6863
 6864
 6865
 6866
 6867
 6868
 6869
 6870
 6871
 6872
 6873
 6874
 6875
 6876
 6877
 6878
 6879
 6880
 6881
 6882
 6883
 6884
 6885
 6886
 6887
 6888
 6889
 6890
 6891
 6892
 6893
 6894
 6895
 6896
 6897
 6898
 6899
 6900
 6901
 6902
 6903
 6904
 6905
 6906
 6907
 6908
 6909
 6910
 6911
 6912
 6913
 6914
 6915
 6916
 6917
 6918
 6919
 6920
 6921
 6922
 6923
 6924
 6925
 6926
 6927
 6928
 6929
 6930
 6931
 6932
 6933
 6934
 6935
 6936
 6937
 6938
 6939
 6940
 6941
 6942
 6943
 6944
 6945
 6946
 6947
 6948
 6949
 6950
 6951
 6952
 6953
 6954
 6955
 6956
 6957
 6958
 6959
 6960
 6961
 6962
 6963
 6964
 6965
 6966
 6967
 6968
 6969
 6970
 6971
 6972
 6973
 6974
 6975
 6976
 6977
 6978
 6979
 6980
 6981
 6982
 6983
 6984
 6985
 6986
 6987
 6988
 6989
 6990
 6991
 6992
 6993
 6994
 6995
 6996
 6997
 6998
 6999
 7000
 7001
 7002
 7003
 7004
 7005
 7006
 7007
 7008
 7009
 7010
 7011
 7012
 7013
 7014
 7015
 7016
 7017
 7018
 7019
 7020
 7021
 7022
 7023
 7024
 7025
 7026
 7027
 7028
 7029
 7030
 7031
 7032
 7033
 7034
 7035
 7036
 7037
 7038
 7039
 7040
 7041
 7042
 7043
 7044
 7045
 7046
 7047
 7048
 7049
 7050
 7051
 7052
 7053
 7054
 7055
 7056
 7057
 7058
 7059
 7060
 7061
 7062
 7063
 7064
 7065
 7066
 7067
 7068
 7069
 7070
 7071
 7072
 7073
 7074
 7075
 7076
 7077
 7078
 7079
 7080
 7081
 7082
 7083
 7084
 7085
 7086
 7087
 7088
 7089
 7090
 7091
 7092
 7093
 7094
 7095
 7096
 7097
 7098
 7099
 7100
 7101
 7102
 7103
 7104
 7105
 7106
 7107
 7108
 7109
 7110
 7111
 7112
 7113
 7114
 7115
 7116
 7117
 7118
 7119
 7120
 7121
 7122
 7123
 7124
 7125
 7126
 7127
 7128
 7129
 7130
 7131
 7132
 7133
 7134
 7135
 7136
 7137
 7138
 7139
 7140
 7141
 7142
 7143
 7144
 7145
 7146
 7147
 7148
 7149
 7150
 7151
 7152
 7153
 7154
 7155
 7156
 7157
 7158
 7159
 7160
 7161
 7162
 7163
 7164
 7165
 7166
 7167
 7168
 7169
 7170
 7171
 7172
 7173
 7174
 7175
 7176
 7177
 7178
 7179
 7180
 7181
 7182
 7183
 7184
 7185
 7186
 7187
 7188
 7189
 7190
 7191
 7192
 7193
 7194
 7195
 7196
 7197
 7198
 7199
 7200
 7201
 7202
 7203
 7204
 7205
 7206
 7207
 7208
 7209
 7210
 7211
 7212
 7213
 7214
 7215
 7216
 7217
 7218
 7219
 7220
 7221
 7222
 7223
 7224
 7225
 7226
 7227
 7228
 7229
 7230
 7231
 7232
 7233
 7234
 7235
 7236
 7237
 7238
 7239
 7240
 7241
 7242
 7243
 7244
 7245
 7246
 7247
 7248
 7249
 7250
 7251
 7252
 7253
 7254
 7255
 7256
 7257
 7258
 7259
 7260
 7261
 7262
 7263
 7264
 7265
 7266
 7267
 7268
 7269
 7270
 7271
 7272
 7273
 7274
 7275
 7276
 7277
 7278
 7279
 7280
 7281
 7282
 7283
 7284
 7285
 7286
 7287
 7288
 7289
 7290
 7291
 7292
 7293
 7294
 7295
 7296
 7297
 7298
 7299
 7300
 7301
 7302
 7303
 7304
 7305
 7306
 7307
 7308
 7309
 7310
 7311
 7312
 7313
 7314
 7315
 7316
 7317
 7318
 7319
 7320
 7321
 7322
 7323
 7324
 7325
 7326
 7327
 7328
 7329
 7330
 7331
 7332
 7333
 7334
 7335
 7336
 7337
 7338
 7339
 7340
 7341
 7342
 7343
 7344
 7345
 7346
 7347
 7348
 7349
 7350
 7351
 7352
 7353
 7354
 7355
 7356
 7357
 7358
 7359
 7360
 7361
 7362
 7363
 7364
 7365
 7366
 7367
 7368
 7369
 7370
 7371
 7372
 7373
 7374
 7375
 7376
 7377
 7378
 7379
 7380
 7381
 7382
 7383
 7384
 7385
 7386
 7387
 7388
 7389
 7390
 7391
 7392
 7393
 7394
 7395
 7396
 7397
 7398
 7399
 7400
 7401
 7402
 7403
 7404
 7405
 7406
 7407
 7408
 7409
 7410
 7411
 7412
 7413
 7414
 7415
 7416
 7417
 7418
 7419
 7420
 7421
 7422
 7423
 7424
 7425
 7426
 7427
 7428
 7429
 7430
 7431
 7432
 7433
 7434
 7435
 7436
 7437
 7438
 7439
 7440
 7441
 7442
 7443
 7444
 7445
 7446
 7447
 7448
 7449
 7450
 7451
 7452
 7453
 7454
 7455
 7456
 7457
 7458
 7459
 7460
 7461
 7462
 7463
 7464
 7465
 7466
 7467
 7468
 7469
 7470
 7471
 7472
 7473
 7474
 7475
 7476
 7477
 7478
 7479
 7480
 7481
 7482
 7483
 7484
 7485
 7486
 7487
 7488
 7489
 7490
 7491
 7492
 7493
 7494
 7495
 7496
 7497
 7498
 7499
 7500
 7501
 7502
 7503
 7504
 7505
 7506
 7507
 7508
 7509
 7510
 7511
 7512
 7513
 7514
 7515
 7516
 7517
 7518
 7519
 7520
 7521
 7522
 7523
 7524
 7525
 7526
 7527
 7528
 7529
 7530
 7531
 7532
 7533
 7534
 7535
 7536
 7537
 7538
 7539
 7540
 7541
 7542
 7543
 7544
 7545
 7546
 7547
 7548
 7549
 7550
 7551
 7552
 7553
 7554
 7555
 7556
 7557
 7558
 7559
 7560
 7561
 7562
 7563
 7564
 7565
 7566
 7567
 7568
 7569
 7570
 7571
 7572
 7573
 7574
 7575
 7576
 7577
 7578
 7579
 7580
 7581
 7582
 7583
 7584
 7585
 7586
 7587
 7588
 7589
 7590
 7591
 7592
 7593
 7594
 7595
 7596
 7597
 7598
 7599
 7600
 7601
 7602
 7603
 7604
 7605
 7606
 7607
 7608
 7609
 7610
 7611
 7612
 7613
 7614
 7615
 7616
 7617
 7618
 7619
 7620
 7621
 7622
 7623
 7624
 7625
 7626
 7627
 7628
 7629
 7630
 7631
 7632
 7633
 7634
 7635
 7636
 7637
 7638
 7639
 7640
 7641
 7642
 7643
 7644
 7645
 7646
 7647
 7648
 7649
 7650
 7651
 7652
 7653
 7654
 7655
 7656
 7657
 7658
 7659
 7660
 7661
 7662
 7663
 7664
 7665
 7666
 7667
 7668
 7669
 7670
 7671
 7672
 7673
 7674
 7675
 7676
 7677
 7678
 7679
 7680
 7681
 7682
 7683
 7684
 7685
 7686
 7687
 7688
 7689
 7690
 7691
 7692
 7693
 7694
 7695
 7696
 7697
 7698
 7699
 7700
 7701
 7702
 7703
 7704
 7705
 7706
 7707
 7708
 7709
 7710
 7711
 7712
 7713
 7714
 7715
 7716
 7717
 7718
 7719
 7720
 7721
 7722
 7723
 7724
 7725
 7726
 7727
 7728
 7729
 7730
 7731
 7732
 7733
 7734
 7735
 7736
 7737
 7738
 7739
 7740
 7741
 7742
 7743
 7744
 7745
 7746
 7747
 7748
 7749
 7750
 7751
 7752
 7753
 7754
 7755
 7756
 7757
 7758
 7759
 7760
 7761
 7762
 7763
 7764
 7765
 7766
 7767
 7768
 7769
 7770
 7771
 7772
 7773
 7774
 7775
 7776
 7777
 7778
 7779
 7780
 7781
 7782
 7783
 7784
 7785
 7786
 7787
 7788
 7789
 7790
 7791
 7792
 7793
 7794
 7795
 7796
 7797
 7798
 7799
 7800
 7801
 7802
 7803
 7804
 7805
 7806
 7807
 7808
 7809
 7810
 7811
 7812
 7813
 7814
 7815
 7816
 7817
 7818
 7819
 7820
 7821
 7822
 7823
 7824
 7825
 7826
 7827
 7828
 7829
 7830
 7831
 7832
 7833
 7834
 7835
 7836
 7837
 7838
 7839
 7840
 7841
 7842
 7843
 7844
 7845
 7846
 7847
 7848
 7849
 7850
 7851
 7852
 7853
 7854
 7855
 7856
 7857
 7858
 7859
 7860
 7861
 7862
 7863
 7864
 7865
 7866
 7867
 7868
 7869
 7870
 7871
 7872
 7873
 7874
 7875
 7876
 7877
 7878
 7879
 7880
 7881
 7882
 7883
 7884
 7885
 7886
 7887
 7888
 7889
 7890
 7891
 7892
 7893
 7894
 7895
 7896
 7897
 7898
 7899
 7900
 7901
 7902
 7903
 7904
 7905
 7906
 7907
 7908
 7909
 7910
 7911
 7912
 7913
 7914
 7915
 7916
 7917
 7918
 7919
 7920
 7921
 7922
 7923
 7924
 7925
 7926
 7927
 7928
 7929
 7930
 7931
 7932
 7933
 7934
 7935
 7936
 7937
 7938
 7939
 7940
 7941
 7942
 7943
 7944
 7945
 7946
 7947
 7948
 7949
 7950
 7951
 7952
 7953
 7954
 7955
 7956
 7957
 7958
 7959
 7960
 7961
 7962
 7963
 7964
 7965
 7966
 7967
 7968
 7969
 7970
 7971
 7972
 7973
 7974
 7975
 7976
 7977
 7978
 7979
 7980
 7981
 7982
 7983
 7984
 7985
 7986
 7987
 7988
 7989
 7990
 7991
 7992
 7993
 7994
 7995
 7996
 7997
 7998
 7999
 8000
 8001
 8002
 8003
 8004
 8005
 8006
 8007
 8008
 8009
 8010
 8011
 8012
 8013
 8014
 8015
 8016
 8017
 8018
 8019
 8020
 8021
 8022
 8023
 8024
 8025
 8026
 8027
 8028
 8029
 8030
 8031
 8032
 8033
 8034
 8035
 8036
 8037
 8038
 8039
 8040
 8041
 8042
 8043
 8044
 8045
 8046
 8047
 8048
 8049
 8050
 8051
 8052
 8053
 8054
 8055
 8056
 8057
 8058
 8059
 8060
 8061
 8062
 8063
 8064
 8065
 8066
 8067
 8068
 8069
 8070
 8071
 8072
 8073
 8074
 8075
 8076
 8077
 8078
 8079
 8080
 8081
 8082
 8083
 8084
 8085
 8086
 8087
 8088
 8089
 8090
 8091
 8092
 8093
 8094
 8095
 8096
 8097
 8098
 8099
 8100
 8101
 8102
 8103
 8104
 8105
 8106
 8107
 8108
 8109
 8110
 8111
 8112
 8113
 8114
 8115
 8116
 8117
 8118
 8119
 8120
 8121
 8122
 8123
 8124
 8125
 8126
 8127
 8128
 8129
 8130
 8131
 8132
 8133
 8134
 8135
 8136
 8137
 8138
 8139
 8140
 8141
 8142
 8143
 8144
 8145
 8146
 8147
 8148
 8149
 8150
 8151
 8152
 8153
 8154
 8155
 8156
 8157
 8158
 8159
 8160
 8161
 8162
 8163
 8164
 8165
 8166
 8167
 8168
 8169
 8170
 8171
 8172
 8173
 8174
 8175
 8176
 8177
 8178
 8179
 8180
 8181
 8182
 8183
 8184
 8185
 8186
 8187
 8188
 8189
 8190
 8191
 8192
 8193
 8194
 8195
 8196
 8197
 8198
 8199
 8200
 8201
 8202
 8203
 8204
 8205
 8206
 8207
 8208
 8209
 8210
 8211
 8212
 8213
 8214
 8215
 8216
 8217
 8218
 8219
 8220
 8221
 8222
 8223
 8224
 8225
 8226
 8227
 8228
 8229
 8230
 8231
 8232
 8233
 8234
 8235
 8236
 8237
 8238
 8239
 8240
 8241
 8242
 8243
 8244
 8245
 8246
 8247
 8248
 8249
 8250
 8251
 8252
 8253
 8254
 8255
 8256
 8257
 8258
 8259
 8260
 8261
 8262
 8263
 8264
 8265
 8266
 8267
 8268
 8269
 8270
 8271
 8272
 8273
 8274
 8275
 8276
 8277
 8278
 8279
 8280
 8281
 8282
 8283
 8284
 8285
 8286
 8287
 8288
 8289
 8290
 8291
 8292
 8293
 8294
 8295
 8296
 8297
 8298
 8299
 8300
 8301
 8302
 8303
 8304
 8305
 8306
 8307
 8308
 8309
 8310
 8311
 8312
 8313
 8314
 8315
 8316
 8317
 8318
 8319
 8320
 8321
 8322
 8323
 8324
 8325
 8326
 8327
 8328
 8329
 8330
 8331
 8332
 8333
 8334
 8335
 8336
 8337
 8338
 8339
 8340
 8341
 8342
 8343
 8344
 8345
 8346
 8347
 8348
 8349
 8350
 8351
 8352
 8353
 8354
 8355
 8356
 8357
 8358
 8359
 8360
 8361
 8362
 8363
 8364
 8365
 8366
 8367
 8368
 8369
 8370
 8371
 8372
 8373
 8374
 8375
 8376
 8377
 8378
 8379
 8380
 8381
 8382
 8383
 8384
 8385
 8386
 8387
 8388
 8389
 8390
 8391
 8392
 8393
 8394
 8395
 8396
 8397
 8398
 8399
 8400
 8401
 8402
 8403
 8404
 8405
 8406
 8407
 8408
 8409
 8410
 8411
 8412
 8413
 8414
 8415
 8416
 8417
 8418
 8419
 8420
 8421
 8422
 8423
 8424
 8425
 8426
 8427
 8428
 8429
 8430
 8431
 8432
 8433
 8434
 8435
 8436
 8437
 8438
 8439
 8440
 8441
 8442
 8443
 8444
 8445
 8446
 8447
 8448
 8449
 8450
 8451
 8452
 8453
 8454
 8455
 8456
 8457
 8458
 8459
 8460
 8461
 8462
 8463
 8464
 8465
 8466
 8467
 8468
 8469
 8470
 8471
 8472
 8473
 8474
 8475
 8476
 8477
 8478
 8479
 8480
 8481
 8482
 8483
 8484
 8485
 8486
 8487
 8488
 8489
 8490
 8491
 8492
 8493
 8494
 8495
 8496
 8497
 8498
 8499
 8500
 8501
 8502
 8503
 8504
 8505
 8506
 8507
 8508
 8509
 8510
 8511
 8512
 8513
 8514
 8515
 8516
 8517
 8518
 8519
 8520
 8521
 8522
 8523
 8524
 8525
 8526
 8527
 8528
 8529
 8530
 8531
 8532
 8533
 8534
 8535
 8536
 8537
 8538
 8539
 8540
 8541
 8542
 8543
 8544
 8545
 8546
 8547
 8548
 8549
 8550
 8551
 8552
 8553
 8554
 8555
 8556
 8557
 8558
 8559
 8560
 8561
 8562
 8563
 8564
 8565
 8566
 8567
 8568
 8569
 8570
 8571
 8572
 8573
 8574
 8575
 8576
 8577
 8578
 8579
 8580
 8581
 8582
 8583
 8584
 8585
 8586
 8587
 8588
 8589
 8590
 8591
 8592
 8593
 8594
 8595
 8596
 8597
 8598
 8599
 8600
 8601
 8602
 8603
 8604
 8605
 8606
 8607
 8608
 8609
 8610
 8611
 8612
 8613
 8614
 8615
 8616
 8617
 8618
 8619
 8620
 8621
 8622
 8623
 8624
 8625
 8626
 8627
 8628
 8629
 8630
 8631
 8632
 8633
 8634
 8635
 8636
 8637
 8638
 8639
 8640
 8641
 8642
 8643
 8644
 8645
 8646
 8647
 8648
 8649
 8650
 8651
 8652
 8653
 8654
 8655
 8656
 8657
 8658
 8659
 8660
 8661
 8662
 8663
 8664
 8665
 8666
 8667
 8668
 8669
 8670
 8671
 8672
 8673
 8674
 8675
 8676
 8677
 8678
 8679
 8680
 8681
 8682
 8683
 8684
 8685
 8686
 8687
 8688
 8689
 8690
 8691
 8692
 8693
 8694
 8695
 8696
 8697
 8698
 8699
 8700
 8701
 8702
 8703
 8704
 8705
 8706
 8707
 8708
 8709
 8710
 8711
 8712
 8713
 8714
 8715
 8716
 8717
 8718
 8719
 8720
 8721
 8722
 8723
 8724
 8725
 8726
 8727
 8728
 8729
 8730
 8731
 8732
 8733
 8734
 8735
 8736
 8737
 8738
 8739
 8740
 8741
 8742
 8743
 8744
 8745
 8746
 8747
 8748
 8749
 8750
 8751
 8752
 8753
 8754
 8755
 8756
 8757
 8758
 8759
 8760
 8761
 8762
 8763
 8764
 8765
 8766
 8767
 8768
 8769
 8770
 8771
 8772
 8773
 8774
 8775
 8776
 8777
 8778
 8779
 8780
 8781
 8782
 8783
 8784
 8785
 8786
 8787
 8788
 8789
 8790
 8791
 8792
 8793
 8794
 8795
 8796
 8797
 8798
 8799
 8800
 8801
 8802
 8803
 8804
 8805
 8806
 8807
 8808
 8809
 8810
 8811
 8812
 8813
 8814
 8815
 8816
 8817
 8818
 8819
 8820
 8821
 8822
 8823
 8824
 8825
 8826
 8827
 8828
 8829
 8830
 8831
 8832
 8833
 8834
 8835
 8836
 8837
 8838
 8839
 8840
 8841
 8842
 8843
 8844
 8845
 8846
 8847
 8848
 8849
 8850
 8851
 8852
 8853
 8854
 8855
 8856
 8857
 8858
 8859
 8860
 8861
 8862
 8863
 8864
 8865
 8866
 8867
 8868
 8869
 8870
 8871
 8872
 8873
 8874
 8875
 8876
 8877
 8878
 8879
 8880
 8881
 8882
 8883
 8884
 8885
 8886
 8887
 8888
 8889
 8890
 8891
 8892
 8893
 8894
 8895
 8896
 8897
 8898
 8899
 8900
 8901
 8902
 8903
 8904
 8905
 8906
 8907
 8908
 8909
 8910
 8911
 8912
 8913
 8914
 8915
 8916
 8917
 8918
 8919
 8920
 8921
 8922
 8923
 8924
 8925
 8926
 8927
 8928
 8929
 8930
 8931
 8932
 8933
 8934
 8935
 8936
 8937
 8938
 8939
 8940
 8941
 8942
 8943
 8944
 8945
 8946
 8947
 8948
 8949
 8950
 8951
 8952
 8953
 8954
 8955
 8956
 8957
 8958
 8959
 8960
 8961
 8962
 8963
 8964
 8965
 8966
 8967
 8968
 8969
 8970
 8971
 8972
 8973
 8974
 8975
 8976
 8977
 8978
 8979
 8980
 8981
 8982
 8983
 8984
 8985
 8986
 8987
 8988
 8989
 8990
 8991
 8992
 8993
 8994
 8995
 8996
 8997
 8998
 8999
 9000
 9001
 9002
 9003
 9004
 9005
 9006
 9007
 9008
 9009
 9010
 9011
 9012
 9013
 9014
 9015
 9016
 9017
 9018
 9019
 9020
 9021
 9022
 9023
 9024
 9025
 9026
 9027
 9028
 9029
 9030
 9031
 9032
 9033
 9034
 9035
 9036
 9037
 9038
 9039
 9040
 9041
 9042
 9043
 9044
 9045
 9046
 9047
 9048
 9049
 9050
 9051
 9052
 9053
 9054
 9055
 9056
 9057
 9058
 9059
 9060
 9061
 9062
 9063
 9064
 9065
 9066
 9067
 9068
 9069
 9070
 9071
 9072
 9073
 9074
 9075
 9076
 9077
 9078
 9079
 9080
 9081
 9082
 9083
 9084
 9085
 9086
 9087
 9088
 9089
 9090
 9091
 9092
 9093
 9094
 9095
 9096
 9097
 9098
 9099
 9100
 9101
 9102
 9103
 9104
 9105
 9106
 9107
 9108
 9109
 9110
 9111
 9112
 9113
 9114
 9115
 9116
 9117
 9118
 9119
 9120
 9121
 9122
 9123
 9124
 9125
 9126
 9127
 9128
 9129
 9130
 9131
 9132
 9133
 9134
 9135
 9136
 9137
 9138
 9139
 9140
 9141
 9142
 9143
 9144
 9145
 9146
 9147
 9148
 9149
 9150
 9151
 9152
 9153
 9154
 9155
 9156
 9157
 9158
 9159
 9160
 9161
 9162
 9163
 9164
 9165
 9166
 9167
 9168
 9169
 9170
 9171
 9172
 9173
 9174
 9175
 9176
 9177
 9178
 9179
 9180
 9181
 9182
 9183
 9184
 9185
 9186
 9187
 9188
 9189
 9190
 9191
 9192
 9193
 9194
 9195
 9196
 9197
 9198
 9199
 9200
 9201
 9202
 9203
 9204
 9205
 9206
 9207
 9208
 9209
 9210
 9211
 9212
 9213
 9214
 9215
 9216
 9217
 9218
 9219
 9220
 9221
 9222
 9223
 9224
 9225
 9226
 9227
 9228
 9229
 9230
 9231
 9232
 9233
 9234
 9235
 9236
 9237
 9238
 9239
 9240
 9241
 9242
 9243
 9244
 9245
 9246
 9247
 9248
 9249
 9250
 9251
 9252
 9253
 9254
 9255
 9256
 9257
 9258
 9259
 9260
 9261
 9262
 9263
 9264
 9265
 9266
 9267
 9268
 9269
 9270
 9271
 9272
 9273
 9274
 9275
 9276
 9277
 9278
 9279
 9280
 9281
 9282
 9283
 9284
 9285
 9286
 9287
 9288
 9289
 9290
 9291
 9292
 9293
 9294
 9295
 9296
 9297
 9298
 9299
 9300
 9301
 9302
 9303
 9304
 9305
 9306
 9307
 9308
 9309
 9310
 9311
 9312
 9313
 9314
 9315
 9316
 9317
 9318
 9319
 9320
 9321
 9322
 9323
 9324
 9325
 9326
 9327
 9328
 9329
 9330
 9331
 9332
 9333
 9334
 9335
 9336
 9337
 9338
 9339
 9340
 9341
 9342
 9343
 9344
 9345
 9346
 9347
 9348
 9349
 9350
 9351
 9352
 9353
 9354
 9355
 9356
 9357
 9358
 9359
 9360
 9361
 9362
 9363
 9364
 9365
 9366
 9367
 9368
 9369
 9370
 9371
 9372
 9373
 9374
 9375
 9376
 9377
 9378
 9379
 9380
 9381
 9382
 9383
 9384
 9385
 9386
 9387
 9388
 9389
 9390
 9391
 9392
 9393
 9394
 9395
 9396
 9397
 9398
 9399
 9400
 9401
 9402
 9403
 9404
 9405
 9406
 9407
 9408
 9409
 9410
 9411
 9412
 9413
 9414
 9415
 9416
 9417
 9418
 9419
 9420
 9421
 9422
 9423
 9424
 9425
 9426
 9427
 9428
 9429
 9430
 9431
 9432
 9433
 9434
 9435
 9436
 9437
 9438
 9439
 9440
 9441
 9442
 9443
 9444
 9445
 9446
 9447
 9448
 9449
 9450
 9451
 9452
 9453
 9454
 9455
 9456
 9457
 9458
 9459
 9460
 9461
 9462
 9463
 9464
 9465
 9466
 9467
 9468
 9469
 9470
 9471
 9472
 9473
 9474
 9475
 9476
 9477
 9478
 9479
 9480
 9481
 9482
 9483
 9484
 9485
 9486
 9487
 9488
 9489
 9490
 9491
 9492
 9493
 9494
 9495
 9496
 9497
 9498
 9499
 9500
 9501
 9502
 9503
 9504
 9505
 9506
 9507
 9508
 9509
 9510
 9511
 9512
 9513
 9514
 9515
 9516
 9517
 9518
 9519
 9520
 9521
 9522
 9523
 9524
 9525
 9526
 9527
 9528
 9529
 9530
 9531
 9532
 9533
 9534
 9535
 9536
 9537
 9538
 9539
 9540
 9541
 9542
 9543
 9544
 9545
 9546
 9547
 9548
 9549
 9550
 9551
 9552
 9553
 9554
 9555
 9556
 9557
 9558
 9559
 9560
 9561
 9562
 9563
 9564
 9565
 9566
 9567
 9568
 9569
 9570
 9571
 9572
 9573
 9574
 9575
 9576
 9577
 9578
 9579
 9580
 9581
 9582
 9583
 9584
 9585
 9586
 9587
 9588
 9589
 9590
 9591
 9592
 9593
 9594
 9595
 9596
 9597
 9598
 9599
 9600
 9601
 9602
 9603
 9604
 9605
 9606
 9607
 9608
 9609
 9610
 9611
 9612
 9613
 9614
 9615
 9616
 9617
 9618
 9619
 9620
 9621
 9622
 9623
 9624
 9625
 9626
 9627
 9628
 9629
 9630
 9631
 9632
 9633
 9634
 9635
 9636
 9637
 9638
 9639
 9640
 9641
 9642
 9643
 9644
 9645
 9646
 9647
 9648
 9649
 9650
 9651
 9652
 9653
 9654
 9655
 9656
 9657
 9658
 9659
 9660
 9661
 9662
 9663
 9664
 9665
 9666
 9667
 9668
 9669
 9670
 9671
 9672
 9673
 9674
 9675
 9676
 9677
 9678
 9679
 9680
 9681
 9682
 9683
 9684
 9685
 9686
 9687
 9688
 9689
 9690
 9691
 9692
 9693
 9694
 9695
 9696
 9697
 9698
 9699
 9700
 9701
 9702
 9703
 9704
 9705
 9706
 9707
 9708
 9709
 9710
 9711
 9712
 9713
 9714
 9715
 9716
 9717
 9718
 9719
 9720
 9721
 9722
 9723
 9724
 9725
 9726
 9727
 9728
 9729
 9730
 9731
 9732
 9733
 9734
 9735
 9736
 9737
 9738
 9739
 9740
 9741
 9742
 9743
 9744
 9745
 9746
 9747
 9748
 9749
 9750
 9751
 9752
 9753
 9754
 9755
 9756
 9757
 9758
 9759
 9760
 9761
 9762
 9763
 9764
 9765
 9766
 9767
 9768
 9769
 9770
 9771
 9772
 9773
 9774
 9775
 9776
 9777
 9778
 9779
 9780
 9781
 9782
 9783
 9784
 9785
 9786
 9787
 9788
 9789
 9790
 9791
 9792
 9793
 9794
 9795
 9796
 9797
 9798
 9799
 9800
 9801
 9802
 9803
 9804
 9805
 9806
 9807
 9808
 9809
 9810
 9811
 9812
 9813
 9814
 9815
 9816
 9817
 9818
 9819
 9820
 9821
 9822
 9823
 9824
 9825
 9826
 9827
 9828
 9829
 9830
 9831
 9832
 9833
 9834
 9835
 9836
 9837
 9838
 9839
 9840
 9841
 9842
 9843
 9844
 9845
 9846
 9847
 9848
 9849
 9850
 9851
 9852
 9853
 9854
 9855
 9856
 9857
 9858
 9859
 9860
 9861
 9862
 9863
 9864
 9865
 9866
 9867
 9868
 9869
 9870
 9871
 9872
 9873
 9874
 9875
 9876
 9877
 9878
 9879
 9880
 9881
 9882
 9883
 9884
 9885
 9886
 9887
 9888
 9889
 9890
 9891
 9892
 9893
 9894
 9895
 9896
 9897
 9898
 9899
 9900
 9901
 9902
 9903
 9904
 9905
 9906
 9907
 9908
 9909
 9910
 9911
 9912
 9913
 9914
 9915
 9916
 9917
 9918
 9919
 9920
 9921
 9922
 9923
 9924
 9925
 9926
 9927
 9928
 9929
 9930
 9931
 9932
 9933
 9934
 9935
 9936
 9937
 9938
 9939
 9940
 9941
 9942
 9943
 9944
 9945
 9946
 9947
 9948
 9949
 9950
 9951
 9952
 9953
 9954
 9955
 9956
 9957
 9958
 9959
 9960
 9961
 9962
 9963
 9964
 9965
 9966
 9967
 9968
 9969
 9970
 9971
 9972
 9973
 9974
 9975
 9976
 9977
 9978
 9979
 9980
 9981
 9982
 9983
 9984
 9985
 9986
 9987
 9988
 9989
 9990
 9991
 9992
 9993
 9994
 9995
 9996
 9997
 9998
 9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
////////////////////////////////////////////////////////////////////////////////
//
//  MILLENIUM-STUDIO
//  Copyright 2016 Millenium-studio SARL
//  All Rights Reserved.
//
////////////////////////////////////////////////////////////////////////////////

#include "AnticheatMgr.h"
#include "Common.h"
#include "Language.h"
#include "DatabaseEnv.h"
#include "Log.h"
#include "Opcodes.h"
#include "SpellMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "UpdateMask.h"
#include "Player.h"
#include "Vehicle.h"
#include "SkillDiscovery.h"
#include "QuestDef.h"
#include "GossipDef.h"
#include "UpdateData.h"
#include "Channel.h"
#include "ChannelMgr.h"
#include "MapManager.h"
#include "MapInstanced.h"
#include "InstanceSaveMgr.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
#include "ObjectMgr.h"
#include "GuildMgr.h"
#include "GroupMgr.h"
#include "ObjectAccessor.h"
#include "CreatureAI.h"
#include "Formulas.h"
#include "Group.h"
#include "Guild.h"
#include "Pet.h"
#include "Util.h"
#include "Transport.h"
#include "Weather.h"
#include "Battleground.h"
#include "BattlegroundAV.h"
#include "BattlegroundMgr.hpp"
#include "OutdoorPvP.h"
#include "OutdoorPvPMgr.h"
#include "Arena.h"
#include "Chat.h"
#include "Spell.h"
#include "SocialMgr.h"
#include "GameEventMgr.h"
#include "AchievementMgr.h"
#include "SpellAuras.h"
#include "SpellAuraEffects.h"
#include "ConditionMgr.h"
#include "DisableMgr.h"
#include "WeatherMgr.h"
#include "LFGMgr.h"
#include "CharacterDatabaseCleaner.h"
#include "InstanceScript.h"
#include "AccountMgr.h"
#include "DB2Stores.h"
#include "DBCStores.h"
#include "Battlefield.h"
#include "BattlefieldMgr.h"
#include "BattlefieldMgr.h"
#include "TicketMgr.h"
#include "UpdateFieldFlags.h"
#include "SceneObject.h"
#include "GarrisonMgr.hpp"
#include "../../../scripts/Draenor/Garrison/GarrisonScriptData.hpp"
#include "PetBattle.h"
#include "MSCallback.hpp"
#include "Vignette.hpp"
#include "WowTime.hpp"

#define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS)

enum SkillFieldOffset
{
    SKILL_OFFSET_LINEID     = 0 * 64,
    SKILL_OFFSET_STEP       = 1 * 64,
    SKILL_OFFSET_RANK       = 2 * 64,
    SKILL_OFFSET_UNK        = 3 * 64,
    SKILL_OFFSET_MAX_RANK   = 4 * 64,
    SKILL_OFFSET_MODIFIER   = 5 * 64,
    SKILL_OFFSET_TALENT     = 6 * 64,
};

enum CharacterFlags
{
    CHARACTER_FLAG_NONE                 = 0x00000000,
    CHARACTER_FLAG_UNK1                 = 0x00000001,
    CHARACTER_FLAG_UNK2                 = 0x00000002,
    CHARACTER_LOCKED_FOR_TRANSFER       = 0x00000004,
    CHARACTER_FLAG_UNK4                 = 0x00000008,
    CHARACTER_FLAG_UNK5                 = 0x00000010,
    CHARACTER_FLAG_UNK6                 = 0x00000020,
    CHARACTER_FLAG_UNK7                 = 0x00000040,
    CHARACTER_FLAG_UNK8                 = 0x00000080,
    CHARACTER_FLAG_UNK9                 = 0x00000100,
    CHARACTER_FLAG_UNK10                = 0x00000200,
    CHARACTER_FLAG_HIDE_HELM            = 0x00000400,
    CHARACTER_FLAG_HIDE_CLOAK           = 0x00000800,
    CHARACTER_FLAG_UNK13                = 0x00001000,
    CHARACTER_FLAG_GHOST                = 0x00002000,
    CHARACTER_FLAG_RENAME               = 0x00004000,
    CHARACTER_FLAG_UNK16                = 0x00008000,
    CHARACTER_FLAG_UNK17                = 0x00010000,
    CHARACTER_FLAG_UNK18                = 0x00020000,
    CHARACTER_FLAG_UNK19                = 0x00040000,
    CHARACTER_FLAG_UNK20                = 0x00080000,
    CHARACTER_FLAG_UNK21                = 0x00100000,
    CHARACTER_FLAG_UNK22                = 0x00200000,
    CHARACTER_FLAG_UNK23                = 0x00400000,
    CHARACTER_FLAG_UNK24                = 0x00800000,
    CHARACTER_FLAG_LOCKED_BY_BILLING    = 0x01000000,
    CHARACTER_FLAG_DECLINED             = 0x02000000,
    CHARACTER_FLAG_UNK27                = 0x04000000,
    CHARACTER_FLAG_UNK28                = 0x08000000,
    CHARACTER_FLAG_UNK29                = 0x10000000,
    CHARACTER_FLAG_UNK30                = 0x20000000,
    CHARACTER_FLAG_UNK31                = 0x40000000,
    CHARACTER_FLAG_UNK32                = 0x80000000
};

enum CharacterCustomizeFlags
{
    CHAR_CUSTOMIZE_FLAG_NONE            = 0x00000000,
    CHAR_CUSTOMIZE_FLAG_CUSTOMIZE       = 0x00000001,       // name, gender, etc...
    CHAR_CUSTOMIZE_FLAG_FACTION         = 0x00010000,       // name, gender, faction, etc...
    CHAR_CUSTOMIZE_FLAG_RACE            = 0x00100000        // name, gender, race, etc...
};

// corpse reclaim times
#define DEATH_EXPIRE_STEP (5*MINUTE)
#define MAX_DEATH_COUNT 3

static uint32 gCopseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };

//== TradeData =================================================

TradeData* TradeData::GetTraderData() const
{
    return m_trader->GetTradeData();
}

Item* TradeData::GetItem(TradeSlots slot) const
{
    if (slot >= TRADE_SLOT_COUNT)
        return nullptr;
    
    return m_items[slot] ? m_player->GetItemByGuid(m_items[slot]) : nullptr;
}

bool TradeData::HasItem(uint64 itemGuid) const
{
    for (uint8 i = 0; i < TRADE_SLOT_COUNT; ++i)
        if (m_items[i] == itemGuid)
            return true;

    return false;
}

TradeSlots TradeData::GetTradeSlotForItem(uint64 itemGuid) const
{
    for (uint8 i = 0; i < TRADE_SLOT_COUNT; ++i)
        if (m_items[i] == itemGuid)
            return TradeSlots(i);

    return TRADE_SLOT_INVALID;
}

Item* TradeData::GetSpellCastItem() const
{
    return m_spellCastItem ? m_player->GetItemByGuid(m_spellCastItem) : NULL;
}

void TradeData::SetItem(TradeSlots slot, Item* item)
{
    uint64 itemGuid = item ? item->GetGUID() : 0;

    if (m_items[slot] == itemGuid)
        return;

    m_items[slot] = itemGuid;

    SetAccepted(false);
    GetTraderData()->SetAccepted(false);

    Update();

    // need remove possible trader spell applied to changed item
    if (slot == TRADE_SLOT_TRADED_COUNT)
        GetTraderData()->SetSpell(0);

    // need remove possible player spell applied (possible move reagent)
    SetSpell(0);
}

void TradeData::SetSpell(uint32 spell_id, Item* castItem /*= NULL*/)
{
    uint64 itemGuid = castItem ? castItem->GetGUID() : 0;

    if (m_spell == spell_id && m_spellCastItem == itemGuid)
        return;

    m_spell = spell_id;
    m_spellCastItem = itemGuid;

    SetAccepted(false);
    GetTraderData()->SetAccepted(false);

    Update(true);                                           // send spell info to item owner
    Update(false);                                          // send spell info to caster self
}

void TradeData::SetMoney(uint64 money)
{
    if (m_money == money)
        return;

    m_money = money;

    SetAccepted(false);
    GetTraderData()->SetAccepted(false);

    Update(true);
}

void TradeData::Update(bool forTarget /*= true*/)
{
    if (forTarget)
        m_trader->GetSession()->SendUpdateTrade(true);      // player state for trader
    else
        m_player->GetSession()->SendUpdateTrade(false);     // player state for player
}

void TradeData::SetAccepted(bool state, bool crosssend /*= false*/)
{
    m_accepted = state;

    if (!state)
    {
        if (crosssend)
            m_trader->GetSession()->SendTradeStatus(TRADE_STATUS_UNACCEPTED);
        else
            m_player->GetSession()->SendTradeStatus(TRADE_STATUS_UNACCEPTED);
    }
}

// == KillRewarder ====================================================
// KillRewarder incapsulates logic of rewarding player upon kill with:
// * XP;
// * honor;
// * reputation;
// * kill credit (for quest objectives).
// Rewarding is initiated in two cases: when player kills unit in Unit::Kill()
// and on battlegrounds in Battleground::RewardXPAtKill().
//
// Rewarding algorithm is:
// 1. Initialize internal variables to default values.
// 2. In case when player is in group, initialize variables necessary for group calculations:
// 2.1. _count - number of alive group members within reward distance;
// 2.2. _sumLevel - sum of levels of alive group members within reward distance;
// 2.3. _maxLevel - maximum level of alive group member within reward distance;
// 2.4. _maxNotGrayMember - maximum level of alive group member within reward distance,
//      for whom victim is not gray;
// 2.5. _isFullXP - flag identifying that for all group members victim is not gray,
//      so 100% XP will be rewarded (50% otherwise).
// 3. Reward killer (and group, if necessary).
// 3.1. If killer is in group, reward group.
// 3.1.1. Initialize initial XP amount based on maximum level of group member,
//        for whom victim is not gray.
// 3.1.2. Alter group rate if group is in raid (not for battlegrounds).
// 3.1.3. Reward each group member (even dead) within reward distance (see 4. for more details).
// 3.2. Reward single killer (not group case).
// 3.2.1. Initialize initial XP amount based on killer's level.
// 3.2.2. Reward killer (see 4. for more details).
// 4. Reward player.
// 4.1. Give honor (player must be alive and not on BG).
// 4.2. Give XP.
// 4.2.1. If player is in group, adjust XP:
//        * set to 0 if player's level is more than maximum level of not gray member;
//        * cut XP in half if _isFullXP is false.
// 4.2.2. Apply auras modifying rewarded XP.
// 4.2.3. Give XP to player.
// 4.2.4. If player has pet, reward pet with XP (100% for single player, 50% for group case).
// 4.3. Give reputation (player must not be on BG).
// 4.4. Give kill credit (player must not be in group, or he must be alive or without corpse).
// 5. Credit instance encounter.
// 6. Update guild achievements.
KillRewarder::KillRewarder(Player* killer, Unit* victim, bool isBattleGround) :
    // 1. Initialize internal variables to default values.
    _killer(killer), _victim(victim), _group(killer->GetGroup()),
    _groupRate(1.0f), _maxNotGrayMember(NULL), _count(0), _sumLevel(0), _xp(0),
    _isFullXP(false), _maxLevel(0), _isBattleGround(isBattleGround), _isPvP(false)
{
    // mark the credit as pvp if victim is player
    if (victim->IsPlayer())
        _isPvP = true;
    // or if its owned by player and its not a vehicle
    else if (IS_PLAYER_GUID(victim->GetCharmerOrOwnerGUID()))
        _isPvP = !victim->IsVehicle();

    _InitGroupData();
}

inline void KillRewarder::_InitGroupData()
{
    if (_group)
    {
        // 2. In case when player is in group, initialize variables necessary for group calculations:
        for (GroupReference* itr = _group->GetFirstMember(); itr != NULL; itr = itr->next())
            if (Player* member = itr->getSource())
                if (member->isAlive() && member->IsAtGroupRewardDistance(_victim))
                {
                    const uint8 lvl = member->getLevel();
                    // 2.1. _count - number of alive group members within reward distance;
                    ++_count;
                    // 2.2. _sumLevel - sum of levels of alive group members within reward distance;
                    _sumLevel += lvl;
                    // 2.3. _maxLevel - maximum level of alive group member within reward distance;
                    if (_maxLevel < lvl)
                        _maxLevel = lvl;
                    // 2.4. _maxNotGrayMember - maximum level of alive group member within reward distance,
                    //      for whom victim is not gray;
                    uint32 grayLevel = JadeCore::XP::GetGrayLevel(lvl);
                    if (_victim->getLevel() > grayLevel && (!_maxNotGrayMember || _maxNotGrayMember->getLevel() < lvl))
                        _maxNotGrayMember = member;
                }
        // 2.5. _isFullXP - flag identifying that for all group members victim is not gray,
        //      so 100% XP will be rewarded (50% otherwise).
        _isFullXP = _maxNotGrayMember && (_maxLevel == _maxNotGrayMember->getLevel());
    }
    else
        _count = 1;
}

inline void KillRewarder::_InitXP(Player* player)
{
    // Get initial value of XP for kill.
    // XP is given:
    // * on battlegrounds;
    // * otherwise, not in PvP;
    // * not if killer is on vehicle.
    if (_isBattleGround || (!_isPvP && !_killer->GetVehicle()))
        _xp = JadeCore::XP::Gain(player, _victim);
}

inline void KillRewarder::_RewardHonor(Player* player)
{
    // Rewarded player must be alive.
    if (player->isAlive())
        player->RewardHonor(_victim, _count, -1, true);
}

inline void KillRewarder::_RewardXP(Player* p_Player, float p_Rate)
{
    uint32 l_Xp(_xp);
    if (_group)
    {
        // 4.2.1. If player is in group, adjust XP:
        //        * set to 0 if player's level is more than maximum level of not gray member;
        //        * cut XP in half if _isFullXP is false.
        if (_maxNotGrayMember && p_Player->isAlive() &&
            _maxNotGrayMember->getLevel() >= p_Player->getLevel())
            l_Xp = _isFullXP ?
                uint32(l_Xp * p_Rate) :             // Reward FULL XP if all group members are not gray.
                uint32(l_Xp * p_Rate / 2) + 1;      // Reward only HALF of XP if some of group members are gray.
        else
            l_Xp = 0;
    }
    if (l_Xp)
    {
        // 4.2.2. Apply auras modifying rewarded XP (SPELL_AURA_MOD_XP_PCT).
        Unit::AuraEffectList const& l_Auras = p_Player->GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT);
        for (Unit::AuraEffectList::const_iterator i = l_Auras.begin(); i != l_Auras.end(); ++i)
            AddPct(l_Xp, (*i)->GetAmount());

        // 4.2.3. Calculate expansion penalty
        if (_victim->GetTypeId() == TYPEID_UNIT && p_Player->getLevel() >= GetMaxLevelForExpansion(_victim->ToCreature()->GetCreatureTemplate()->expansion))
            l_Xp = CalculatePct(l_Xp, 10); // Players get only 10% xp for killing creatures of lower expansion levels than himself

        // 4.2.4. Give XP to player.
        p_Player->GiveXP(l_Xp, _victim, _groupRate);
        if (Pet* pet = p_Player->GetPet())
            // 4.2.5. If player has pet, reward pet with XP (100% for single player, 50% for group case).
            pet->GivePetXP(_group ? l_Xp / 2 : l_Xp);

        // Modificate xp for racial aura of trolls (+20% if beast)
        Unit::AuraEffectList const& l_AurasXpPct = p_Player->GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT_FROM_KILLING_UNIT_TYPE);
        for (Unit::AuraEffectList::const_iterator i = l_AurasXpPct.begin(); i != l_AurasXpPct.end(); ++i)
        {
            if (_victim->ToCreature() && _victim->ToCreature()->isType((*i)->GetMiscValue()))
                AddPct(l_Xp, (*i)->GetAmount());
        }
    }
}

inline void KillRewarder::_RewardReputation(Player* player, float rate)
{
    // 4.3. Give reputation (player must not be on BG).
    // Even dead players and corpses are rewarded.
    player->RewardReputation(_victim, rate);
}

inline void KillRewarder::_RewardKillCredit(Player* player)
{
    // 4.4. Give kill credit (player must not be in group, or he must be alive or without corpse).
    if (!_group || player->isAlive() || !player->GetCorpse())
        if (_victim->GetTypeId() == TYPEID_UNIT)
            player->KilledMonster(_victim->ToCreature()->GetCreatureTemplate(), _victim->GetGUID());
}

void KillRewarder::_RewardPlayer(Player* player, bool isDungeon)
{
    // 4. Reward player.
    if (!_isBattleGround)
    {
        // 4.1. Give honor (player must be alive and not on BG).
        _RewardHonor(player);
        // 4.1.1 Send player killcredit for quests with PlayerSlain
        if (_victim->IsPlayer())
            player->KilledPlayerCredit();
    }
    // Give XP only in PvE or in battlegrounds.
    // Give reputation and kill credit only in PvE.
    if (!_isPvP || _isBattleGround)
    {
        const float rate = _group ?
            _groupRate * float(player->getLevel()) / _sumLevel : // Group rate depends on summary level.
            1.0f;                                                // Personal rate is 100%.
        if (_xp)
        {
            // 4.2. Give XP.
            if (!(_victim->getLevel() > player->getLevel() && (_victim->getLevel() - player->getLevel()) > 6 && _group))
                _RewardXP(player, rate);
        }
        if (!_isBattleGround)
        {
            // If killer is in dungeon then all members receive full reputation at kill.
            _RewardReputation(player, isDungeon ? 1.0f : rate);
            _RewardKillCredit(player);
        }
    }
}

void KillRewarder::_RewardGroup()
{
    if (_maxLevel)
    {
        if (_maxNotGrayMember)
            // 3.1.1. Initialize initial XP amount based on maximum level of group member,
            //        for whom victim is not gray.
            _InitXP(_maxNotGrayMember);
        // To avoid unnecessary calculations and calls,
        // proceed only if XP is not ZERO or player is not on battleground
        // (battleground rewards only XP, that's why).
        if (!_isBattleGround || _xp)
        {
            const bool isDungeon = !_isPvP && sMapStore.LookupEntry(_killer->GetMapId())->IsDungeon();
            if (!_isBattleGround)
            {
                // 3.1.2. Alter group rate if group is in raid (not for battlegrounds).
                const bool isRaid = !_isPvP && sMapStore.LookupEntry(_killer->GetMapId())->IsRaid() && _group->isRaidGroup();
                _groupRate = JadeCore::XP::xp_in_group_rate(_count, isRaid);
            }

            // 3.1.3. Reward each group member (even dead or corpse) within reward distance.
            for (GroupReference* itr = _group->GetFirstMember(); itr != NULL; itr = itr->next())
                if (Player* member = itr->getSource())
                    if (member->IsAtGroupRewardDistance(_victim))
                        _RewardPlayer(member, isDungeon);
        }
    }
}

void KillRewarder::Reward()
{
    // 3. Reward killer (and group, if necessary).
    if (_group)
        // 3.1. If killer is in group, reward group.
        _RewardGroup();
    else
    {
        // 3.2. Reward single killer (not group case).
        // 3.2.1. Initialize initial XP amount based on killer's level.
        _InitXP(_killer);
        // To avoid unnecessary calculations and calls,
        // proceed only if XP is not ZERO or player is not on battleground
        // (battleground rewards only XP, that's why).
        if (!_isBattleGround || _xp)
            // 3.2.2. Reward killer.
            _RewardPlayer(_killer, false);
    }


    // 5. Credit instance encounter.
    // 6. Update guild achievements.
    if (Creature* victim = _victim->ToCreature())
    {
        if (InstanceScript* instance = _victim->GetInstanceScript())
            instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, _victim->GetEntry(), _victim);

        if (uint32 guildId = victim->GetMap()->GetOwnerGuildId())
        {
            if (Guild* guild = sGuildMgr->GetGuildById(guildId))
                guild->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, victim->GetEntry(), 1, 0, victim, _killer);
        }
    }
}

bool PetQueryHolder::Initialize()
{
    SetSize(MAX_PET_LOGIN_QUERY);

    bool res = true;

    PreparedStatement* stmt = NULL;

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PET_AURA);
    stmt->setUInt32(0, m_guid);
    res &= SetPreparedQuery(PET_LOGIN_QUERY_LOADAURA, stmt);

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PET_AURA_EFFECT);
    stmt->setUInt32(0, m_guid);
    res &= SetPreparedQuery(PET_LOGIN_QUERY_LOADAURAEFFECT, stmt);

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PET_SPELL);
    stmt->setUInt32(0, m_guid);
    res &= SetPreparedQuery(PET_LOGIN_QUERY_LOADSPELL, stmt);

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PET_SPELL_COOLDOWN);
    stmt->setUInt32(0, m_guid);
    res &= SetPreparedQuery(PET_LOGIN_QUERY_LOADSPELLCOOLDOWN, stmt);

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PET_DECLINED_NAME);
    stmt->setUInt32(0, m_guid);
    res &= SetPreparedQuery(PET_LOGIN_QUERY_DECLINED_NAME, stmt);

    return res;
}

PreparedStatement* PetQueryHolder::GenerateFirstLoadStatement(uint32 p_PetEntry, uint32 p_PetNumber, uint32 p_OwnerID, bool p_CurrentPet, PetSlot p_SlotID)
{
    PreparedStatement* l_Statement = nullptr;

    if (p_PetNumber)
    {
        // Known petnumber entry
        //        0     1      2       3       4     5       6        7     8       9        10        11       12       13           14          15          16
        // SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, abdata, savetime, CreatedBySpell, PetType, specialization
        l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PET_BY_ENTRY);
        l_Statement->setUInt32(0, p_OwnerID);
        l_Statement->setUInt32(1, p_PetNumber);
    }
    else if (p_CurrentPet && p_SlotID != PET_SLOT_UNK_SLOT)
    {
        // Current pet (slot 0)
        //        0     1     2        3       4     5       6        7      8      9        10         11      12      13           14            15          16
        // SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, abdata, savetime, CreatedBySpell, PetType, specialization
        l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PET_BY_ENTRY_AND_SLOT);
        l_Statement->setUInt32(0, p_OwnerID);
        l_Statement->setUInt32(1, p_SlotID);
    }
    else if (p_PetEntry)
    {
        // Known petentry entry (unique for summoned pet, but non unique for hunter pet (only from current or not stabled pets)
        //        0     1     2        3       4     5       6        7      8      9        10         11      12      13           14            15          16
        // SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, abdata, savetime, CreatedBySpell, PetType, specialization
        l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PET_BY_ENTRY_AND_SLOT_2);
        l_Statement->setUInt32(0, p_OwnerID);
        l_Statement->setUInt32(1, p_PetEntry);
        l_Statement->setUInt32(2, PET_SLOT_HUNTER_FIRST);
        l_Statement->setUInt32(3, PET_SLOT_HUNTER_LAST);
        l_Statement->setUInt32(4, PET_SLOT_STABLE_LAST);
    }
    else
    {
        // Any current or other non-stabled pet (for hunter "call pet")
        //        0     1     2        3       4     5       6        7      8      9        10         11      12      13           14            15          16
        // SELECT id, entry, owner, modelid, level, exp, Reactstate, slot, name, renamed, curhealth, curmana, abdata, savetime, CreatedBySpell, PetType, specialization
        l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PET_BY_SLOT);
        l_Statement->setUInt32(0, p_OwnerID);
        l_Statement->setUInt32(1, PET_SLOT_HUNTER_FIRST);
        l_Statement->setUInt32(2, PET_SLOT_HUNTER_LAST);
        l_Statement->setUInt32(3, p_SlotID);
    }

    return l_Statement;
}


// == Player ====================================================
// we can disable this warning for this since it only
// causes undefined behavior when passed to the base class constructor
#ifdef _MSC_VER
#pragma warning(disable:4355)
#endif
Player::Player(WorldSession* session) : Unit(true), m_achievementMgr(this), m_reputationMgr(this), phaseMgr(this), m_archaeologyMgr(this), m_VignetteMgr(this)
{
#ifdef _MSC_VER
#pragma warning(default:4355)
#endif

    m_Garrison = nullptr;
    m_GarrisonUpdateTimer.SetInterval(2 * IN_MILLISECONDS);

    m_VoidStorageLoaded = false;

    CurrentPlayedMovie = 0;

    m_speakTime = 0;
    m_speakCount = 0;

    m_bgRoles = 0;

    m_lastPlayedEmote = 0;

    m_pmChatTime = 0;
    m_pmChatCount = 0;

    m_petSlotUsed = 0;
    m_currentPetSlot = PET_SLOT_DELETED;

    m_objectType |= TYPEMASK_PLAYER;
    m_objectTypeId = TYPEID_PLAYER;

    m_valuesCount = PLAYER_END;
    _dynamicValuesCount = PLAYER_DYNAMIC_END;

    m_session = session;

    m_divider = 0;

    m_ExtraFlags = 0;

    m_tokenCounter = 0;

    m_spellModTakingSpell = NULL;
    //m_pad = 0;

    // players always accept
    if (AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()))
        SetAcceptWhispers(true);

    m_curSelection = 0;
    m_lootGuid = 0;

    m_lootSpecId = 0;
    m_BonusRollFails = 0;

    m_RegenPowerTimer = 0;
    m_regenTimerCount = 0;
    m_holyPowerRegenTimerCount = 0;
    m_runicPowerRegenTimerCount = 0;
    m_chiPowerRegenTimerCount = 0;
    m_demonicFuryPowerRegenTimerCount = 0;
    m_soulShardsRegenTimerCount = 0;
    m_focusRegenTimerCount = 0;
    m_weaponChangeTimer = 0;

    m_zoneUpdateId = 0;
    m_zoneUpdateTimer = 0;

    m_areaUpdateId = 0;

    m_nextSave = sWorld->getIntConfig(CONFIG_INTERVAL_SAVE);

    _resurrectionData = NULL;

    memset(m_items, 0, sizeof(Item*) * PLAYER_SLOTS_COUNT);

    m_social = NULL;

    // group is initialized in the reference constructor
    SetGroupInvite(0);
    m_groupUpdateMask = 0;
    m_auraRaidUpdateMask = 0;
    m_bPassOnGroupLoot = false;

    m_Duel = NULL;

    m_GuildIdInvited = 0;

    m_atLoginFlags = AT_LOGIN_NONE;

    mSemaphoreTeleport_Near = false;
    mSemaphoreTeleport_Far = false;

    m_DelayedOperations = 0;
    m_bCanDelayTeleport = false;
    m_bHasDelayedTeleport = false;
    m_isMoltenCored = false;
    m_teleport_options = 0;

    m_trade = NULL;
    m_ClientStateIndex = 0;

    m_cinematic = 0;

    PlayerTalkClass = new PlayerMenu(GetSession());
    m_currentBuybackSlot = BUYBACK_SLOT_START;

    m_DailyQuestChanged = false;
    m_lastDailyQuestTime = 0;

    for (uint8 i=0; i < MAX_TIMERS; i++)
        m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;

    m_MirrorTimerFlags = UNDERWATER_NONE;
    m_MirrorTimerFlagsLast = UNDERWATER_NONE;
    m_isInWater = false;
    m_drunkTimer = 0;
    m_restTime = 0;
    m_deathTimer = 0;
    m_deathExpireTime = 0;

    m_swingErrorMsg = 0;

    for (uint8 j = 0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
    {
        m_bgBattlegroundQueueID[j].BgType = MS::Battlegrounds::BattlegroundType::None;
        m_bgBattlegroundQueueID[j].invitedToInstance = 0;
    }

    m_logintime = time(NULL);
    m_Last_tick = m_logintime;
    m_WeaponProficiency = 0;
    m_ArmorProficiency = 0;
    m_canParry = false;
    m_canBlock = false;
    m_canDualWield = false;
    m_canTitanGrip = false;

    m_temporaryUnsummonedPetNumber = 0;
    //cache for UNIT_FIELD_CREATED_BY_SPELL to allow
    //returning reagents for temporarily removed pets
    //when dying/logging out
    m_oldpetspell = 0;
    m_lastpetnumber = 0;

    ////////////////////Rest System/////////////////////
    time_inn_enter=0;
    inn_pos_mapid=0;
    inn_pos_x=0;
    inn_pos_y=0;
    inn_pos_z=0;
    m_rest_bonus=0;
    rest_type=REST_TYPE_NO;
    ////////////////////Rest System/////////////////////

    m_mailsUpdated = false;
    unReadMails = 0;
    m_nextMailDelivereTime = 0;

    m_itemUpdateQueueBlocked = false;

    for (uint8 i = 0; i < MAX_MOVE_TYPE; ++i)
        m_forced_speed_changes[i] = 0;

    m_stableSlots = 0;

    /////////////////// Instance System /////////////////////

    m_HomebindTimer = 0;
    m_InstanceValid = true;
    m_dungeonDifficulty = DifficultyNormal;
    m_raidDifficulty = DifficultyRaidNormal;
    m_LegacyRaidDifficulty = Difficulty10N;
    m_PrevMapDifficulty = DifficultyRaidNormal;

    m_lastPotionId = 0;
    _talentMgr = new PlayerTalentInfo();

    m_glyphsChanged = false;

    for (uint8 i = 0; i < BASEMOD_END; ++i)
    {
        m_auraBaseMod[i][FLAT_MOD] = 0.0f;
        m_auraBaseMod[i][PCT_MOD] = 1.0f;
    }

    for (uint8 i = 0; i < MAX_COMBAT_RATING; i++)
        m_baseRatingValue[i] = 0;

    m_baseSpellPower = 0;
    m_baseManaRegen = 0;
    m_baseHealthRegen = 0;
    m_spellPenetrationItemMod = 0;

    // Honor System
    m_lastHonorUpdateTime = time(NULL);

    m_IsBGRandomWinner = false;

    // Player summoning
    m_summon_expire = 0;
    m_summon_mapid = 0;
    m_summon_x = 0.0f;
    m_summon_y = 0.0f;
    m_summon_z = 0.0f;

    m_mover = this;
    m_movedPlayer = this;
    m_seer = this;

    m_contestedPvPTimer = 0;

    m_declinedname = NULL;

    m_isActive = true;

    m_lastFallTime = 0;
    m_lastFallZ = 0;

    m_grantableLevels = 0;

    m_ControlledByPlayer = true;

    sWorld->IncreasePlayerCount();

    m_ChampioningFaction = 0;

    for (uint8 i = 0; i < MAX_POWERS_PER_CLASS; ++i)
        m_powerFraction[i] = 0;

    isDebugAreaTriggers = false;

    m_IsDebugQuestLogs = false;

    m_WeeklyQuestChanged = false;

    m_MonthlyQuestChanged = false;

    m_SeasonalQuestChanged = false;

    SetPendingBind(0, 0);

    _activeCheats = CHEAT_NONE;
    _maxPersonalArenaRate = 0;

    _lastTargetedGO = 0;

    m_PersonnalXpRate = sWorld->getRate(RATE_XP_KILL);

    m_knockBackTimer = 0;

    m_CinematicSequence         = NULL;
    m_InCinematic               = false;
    m_CinematicClientStartTime  = 0;

    m_BattlePetSummon = 0;

    m_ignoreMovementCount = 0;

    m_groupUpdateDelay = 5000;

    m_emote = 0;

    memset(_voidStorageItems, 0, VOID_STORAGE_MAX_SLOT * sizeof(VoidStorageItem*));

    for (uint8 i = 0; i < MAX_PVP_SLOT; ++i)
    {
        m_ArenaPersonalRating[i] = sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING);
        m_BestRatingOfWeek[i] = 0;
        m_BestRatingOfSeason[i] = 0;
        m_ArenaMatchMakerRating[i] = sWorld->getIntConfig(CONFIG_ARENA_START_MATCHMAKER_RATING);
        m_WeekWins[i] = 0;
        m_PrevWeekWins[i] = 0;
        m_SeasonWins[i] = 0;
        m_WeekGames[i] = 0;
        m_SeasonGames[i] = 0;
    }

    for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
    {
        prohibited[i] = prohibited_struct();
    }

    m_initializeCallback = false;

    m_needSummonPetAfterStopFlying = false;

    m_LastPlayedScene = NULL;

    m_PvPCombatTimer = 0;
    m_pvpCombat = false;

    for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
        m_itemScale[i] = 0;

    m_LastSummonedBattlePet = 0;

    for (size_t l_CurrentPetSlot = 0; l_CurrentPetSlot < MAX_PETBATTLE_SLOTS; ++l_CurrentPetSlot)
        m_BattlePetCombatTeam[l_CurrentPetSlot] = BattlePet::Ptr();

    ///////////////////////////////////////////////////////////

    m_WargameRequest = nullptr;

    m_PreviousLocationMapId = MAPID_INVALID;
    m_PreviousLocationX = 0;
    m_PreviousLocationY = 0;
    m_PreviousLocationZ = 0;
    m_PreviousLocationO = 0;

    for (uint8 l_I = 0; l_I < StoreCallback::MaxDelivery; l_I++)
        m_StoreDeliveryProcessed[l_I] = false;

    m_StoreDeliverySave = false;
    m_BeaconOfFaithTargetGUID = 0;

    m_MasteryCache = 0.0f;
}

Player::~Player()
{
    sLFGListMgr->RemovePlayerDueToLogout(GetGUIDLow());

    if (m_Garrison)
        delete m_Garrison;

    if (m_WargameRequest)
        delete m_WargameRequest;

    sSpellLogMgr->RemoveListener(this);

    // it must be unloaded already in PlayerLogout and accessed only for loggined player
    //m_social = NULL;

    // temp check
    for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
    {
        for (uint8 slot = 0; slot < PLAYER_SLOTS_COUNT; slot++)
        {
            if (m_items[slot] == NULL)
                continue;

            if (m_items[i] == m_items[slot] && slot != i)
            {
                sLog->outAshran("Player[%u] have same item pointer in two slot ! (slot: %u, copy slot: %u)", GetGUIDLow(), i, slot);
                m_items[i] = NULL;
            }
        }
    }

    // Note: buy back item already deleted from DB when player was saved
    for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; ++i)
        delete m_items[i];

    for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
        delete itr->second;

    delete _talentMgr;

    //all mailed items should be deleted, also all mail should be deallocated
    for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
        delete *itr;

    for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
        delete iter->second;                                //if item is duplicated... then server may crash ... but that item should be deallocated

    delete PlayerTalkClass;

    for (size_t x = 0; x < ItemSetEff.size(); x++)
        delete ItemSetEff[x];

    delete m_declinedname;

    for (uint8 i = 0; i < VOID_STORAGE_MAX_SLOT; ++i)
        delete _voidStorageItems[i];

    ClearResurrectRequestData();

    sWorld->DecreasePlayerCount();
}

void Player::CleanupsBeforeDelete(bool finalCleanup)
{
    TradeCancel(false);
    DuelComplete(DUEL_INTERRUPTED);

    Unit::CleanupsBeforeDelete(finalCleanup);

    if (m_transport)
        m_transport->RemovePassenger(this);

    // clean up player-instance binds, may unload some instance saves
    for (uint8 i = 0; i < Difficulty::MaxDifficulties; ++i)
        for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
            itr->second.save->RemovePlayer(this);
}

bool Player::Create(uint32 guidlow, CharacterCreateInfo* createInfo)
{
    // @FIXME: outfitId not used in player creating
    // TODO: need more checks against packet modifications
    // should check that skin, face, hair* are valid via DBC per race/class
    // also do it in Player::BuildEnumData, Player::LoadFromDB

    Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
    CharacterTemplate const* l_Template = sObjectMgr->GetCharacterTemplate(createInfo->TemplateId);

    m_name = createInfo->Name;

    ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(createInfo->Class);
    if (!cEntry)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid character class (%u) - refusing to do so (wrong DBC-files?)",
                GetSession()->GetAccountId(), m_name.c_str(), createInfo->Class);
        return false;
    }

    uint8 powertype = cEntry->DisplayPower;

    SetFloatValue(UNIT_FIELD_BOUNDING_RADIUS, DEFAULT_WORLD_OBJECT_SIZE);
    SetFloatValue(UNIT_FIELD_COMBAT_REACH, 1.5f);

    setFactionForRace(createInfo->Race);

    if (!IsValidGender(createInfo->Gender))
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid gender (%hhu) - refusing to do so",
                GetSession()->GetAccountId(), m_name.c_str(), createInfo->Gender);
        return false;
    }

    PlayerInfo const* info = sObjectMgr->GetPlayerInfo(createInfo->Race, createInfo->Class);
    if (!info)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player::Create: Possible hacking-attempt: Account %u tried creating a character named '%s' with an invalid race/class pair (%u/%u) - refusing to do so.",
                GetSession()->GetAccountId(), m_name.c_str(), createInfo->Race, createInfo->Class);
        return false;
    }

    for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
        m_items[i] = NULL;

    if (l_Template && (GetTeam() == HORDE ? l_Template->m_HordeMapID != -1 : l_Template->m_AlianceMapID != -1))
    {
        if (GetTeam() == HORDE)
        {
            Relocate(l_Template->m_HordePos);
            SetMap(sMapMgr->CreateMap(l_Template->m_HordeMapID, this));
        }
        else
        {
            Relocate(l_Template->m_AliancePos);
            SetMap(sMapMgr->CreateMap(l_Template->m_AlianceMapID, this));
        }
    }
    else
    {
        Relocate(info->positionX, info->positionY, info->positionZ, info->orientation);
        SetMap(sMapMgr->CreateMap(info->mapId, this));
    }


    uint32 RaceClassPower = (createInfo->Race) | (createInfo->Class << 8) | (powertype << 16);

    SetUInt32Value(UNIT_FIELD_SEX, (RaceClassPower | (createInfo->Gender << 24)));
    SetUInt32Value(UNIT_FIELD_DISPLAY_POWER, powertype);
    InitDisplayIds();
    if (sWorld->getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || sWorld->getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP)
    {
        SetByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_PVP);
        SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
    }
    SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
    SetFloatValue(UNIT_FIELD_MOD_CASTING_SPEED, 1.0f);               // fix cast time showed in spell tooltip on client
    SetFloatValue(UNIT_FIELD_MOD_SPELL_HASTE, 1.0f);
    SetFloatValue(UNIT_FIELD_MOD_HASTE, 1.0f);
    SetFloatValue(UNIT_FIELD_MOD_HASTE_REGEN, 1.0f);
    SetFloatValue(UNIT_FIELD_MOD_RANGED_HASTE, 1.0f);
    SetFloatValue(UNIT_FIELD_HOVER_HEIGHT, 1.0f);            // default for players in 3.0.3
    SetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER, 0.0f);
    SetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER, 0.0f);

                                                            // -1 is default value
    SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));

    SetByteValue(PLAYER_FIELD_HAIR_COLOR_ID, PLAYER_BYTES_OFFSET_SKIN_ID, createInfo->Skin);
    SetByteValue(PLAYER_FIELD_HAIR_COLOR_ID, PLAYER_BYTES_OFFSET_FACE_ID, createInfo->Face);
    SetByteValue(PLAYER_FIELD_HAIR_COLOR_ID, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID, createInfo->HairStyle);
    SetByteValue(PLAYER_FIELD_HAIR_COLOR_ID, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID, createInfo->HairColor);

    SetByteValue(PLAYER_FIELD_REST_STATE, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE, createInfo->FacialHair);
    SetByteValue(PLAYER_FIELD_REST_STATE, PLAYER_BYTES_2_OFFSET_REST_STATE, (GetSession()->IsARecruiter() || GetSession()->GetRecruiterId() != 0) ? REST_STATE_RAF_LINKED : REST_STATE_NOT_RAF_LINKED);

    SetByteValue(PLAYER_FIELD_ARENA_FACTION, PLAYER_BYTES_3_OFFSET_GENDER, createInfo->Gender);
    SetByteValue(PLAYER_FIELD_ARENA_FACTION, PLAYER_BYTES_3_OFFSET_ARENA_FACTION, 0);               ///< BattlefieldArenaFaction (0 or 1)

    SetGuidValue(OBJECT_FIELD_DATA, 0);
    SetUInt32Value(PLAYER_FIELD_GUILD_RANK_ID, 0);
    SetGuildLevel(0);
    SetUInt32Value(PLAYER_FIELD_GUILD_TIME_STAMP, 0);
    SetUInt32Value(PLAYER_FIELD_VIRTUAL_PLAYER_REALM, g_RealmID);

    for (int i = 0; i < KNOWN_TITLES_SIZE; ++i)
        SetUInt32Value(PLAYER_FIELD_KNOWN_TITLES + i, 0);  // 0=disabled
    SetUInt32Value(PLAYER_FIELD_PLAYER_TITLE, 0);
    SetUInt32Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 0);
    SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, 0);

    // set starting level
    uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
        ? sWorld->getIntConfig(CONFIG_START_PLAYER_LEVEL)
        : sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);

    if (!AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()))
    {
        uint32 gm_level = sWorld->getIntConfig(CONFIG_START_GM_LEVEL);
        if (gm_level > start_level)
            start_level = gm_level;
    }

    if (l_Template)
    {
        SetUInt64Value(PLAYER_FIELD_COINAGE, l_Template->m_Money);
        SetUInt32Value(UNIT_FIELD_LEVEL, l_Template->m_Level);
    }
    else
    {
        SetUInt64Value(PLAYER_FIELD_COINAGE, sWorld->getIntConfig(CONFIG_START_PLAYER_MONEY));
        SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
    }

    InitRunes();

    SetCurrency(CURRENCY_TYPE_HONOR_POINTS, sWorld->getIntConfig(CONFIG_CURRENCY_START_HONOR_POINTS));
    SetCurrency(CURRENCY_TYPE_JUSTICE_POINTS, sWorld->getIntConfig(CONFIG_CURRENCY_START_JUSTICE_POINTS));
    SetCurrency(CURRENCY_TYPE_CONQUEST_POINTS, sWorld->getIntConfig(CONFIG_CURRENCY_START_CONQUEST_POINTS));

    // start with every map explored
    if (sWorld->getBoolConfig(CONFIG_START_ALL_EXPLORED))
    {
        for (uint8 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; i++)
            SetFlag(PLAYER_FIELD_EXPLORED_ZONES +i, 0xFFFFFFFF);
    }

    for (uint8 i = 0; i < MAX_PVP_SLOT; ++i)
    {
        SetArenaPersonalRating(i, sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING));
        SetArenaMatchMakerRating(i, sWorld->getIntConfig(CONFIG_ARENA_START_MATCHMAKER_RATING));
    }

    //Reputations if "StartAllReputation" is enabled, -- TODO: Fix this in a better way
    if (sWorld->getBoolConfig(CONFIG_START_ALL_REP))
    {
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(942), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(935), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(936), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1011), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(970), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(967), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(989), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(932), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(934), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1038), 42999);
        GetReputationMgr().SetReputation(sFactionStore.LookupEntry(1077), 42999);

        // Factions depending on team, like cities and some more stuff
        switch (GetTeam())
        {
            case ALLIANCE:
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(72), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(47), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(69), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(930), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(730), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(978), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(54), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(946), 42999);
                break;
            case HORDE:
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(76), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(68), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(81), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(911), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(729), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(941), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(530), 42999);
                GetReputationMgr().SetReputation(sFactionStore.LookupEntry(947), 42999);
                break;
            default:
                break;
        }
    }

    if (l_Template)
        for (auto& l_ReputationInfo : l_Template->m_TemplateFactions)
            if (FactionEntry const* l_Faction = sFactionStore.LookupEntry(l_ReputationInfo.m_FactionID))
                GetReputationMgr().SetReputation(l_Faction, l_ReputationInfo.m_Reputaion);

    // Played time
    m_Last_tick = time(NULL);
    m_Played_time[PLAYED_TIME_TOTAL] = 0;
    m_Played_time[PLAYED_TIME_LEVEL] = 0;

    // base stats and related field values
    InitStatsForLevel();
    InitTaxiNodesForLevel();
    InitGlyphsForLevel();
    InitTalentForLevel();
    InitSpellForLevel();
    InitPrimaryProfessions();                               // to max set before any spell added

    // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
    UpdateMaxHealth();                                      // Update max Health (for add bonus from stamina)
    SetFullHealth();
    if (getPowerType() == POWER_MANA)
    {
        UpdateMaxPower(POWER_MANA);                         // Update max Mana (for add bonus from intellect)
        SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
    }

    if (getPowerType() == POWER_RUNIC_POWER)
    {
        SetPower(POWER_RUNES, 8);
        SetMaxPower(POWER_RUNES, 8);
        SetPower(POWER_RUNIC_POWER, 0);
        SetMaxPower(POWER_RUNIC_POWER, 1000);
    }

    if (l_Template)
        for (auto l_Spell : l_Template->m_SpellIDs)
            learnSpell(l_Spell, false);

    // original spells
    learnDefaultSpells();

    // original action bar
    for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
        addActionButton(action_itr->button, action_itr->action, action_itr->type);

    if (l_Template)
    {
        std::list<CharacterTemplate::TemplateItem const*> l_RemainingTemplates;
        for (auto& l_Item : l_Template->m_TemplateItems)
        {
            if (ItemTemplate const* l_Proto = sObjectMgr->GetItemTemplate(l_Item.m_ItemID))
            {
                // Give bags first to the players, then the equipment
                if (l_Proto->Class == ITEM_CLASS_CONTAINER)
                {
                    if (!l_Item.m_Faction || (l_Item.m_Faction == 1 && GetTeam() == ALLIANCE) || (l_Item.m_Faction == 2 && GetTeam() == HORDE))
                        StoreNewItemInBestSlots(l_Item.m_ItemID, l_Item.m_Count);
                    continue;
                }
                else
                    l_RemainingTemplates.push_back(&l_Item);
            }
        }

        for (auto l_Item : l_RemainingTemplates)
        {
            if (ItemTemplate const* l_Proto = sObjectMgr->GetItemTemplate(l_Item->m_ItemID))
            {
                if ((l_Proto->AllowableRace & getRaceMask()) == 0)
                    continue;

                if (!l_Item->m_Faction || (l_Item->m_Faction == 1 && GetTeam() == ALLIANCE) || (l_Item->m_Faction == 2 && GetTeam() == HORDE))
                {
                    ItemContext l_ItemContext = ItemContext::None;
                    switch (l_Item->m_Type)
                    {
                        case 1: ///< Shop PvE premade
                            l_ItemContext = ItemContext::RaidLfr;
                            break;
                        case 3: ///< PTR PvE templates
                            l_ItemContext = ItemContext::RaidNormal;
                            break;
                        default:
                            break;
                    }

                    if (l_ItemContext != ItemContext::None)
                        StoreNewItemInBestSlots(l_Item->m_ItemID, l_Item->m_Count, l_ItemContext);
                }
            }
        }
    }
    else
    {
        // original items
        CharStartOutfitEntry const* oEntry = NULL;
        for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
        {
            if (CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
            {
                if (entry->RaceID  == createInfo->Race  &&
                    entry->ClassID == createInfo->Class &&
                    entry->SexID   == createInfo->Gender)
                {
                    oEntry = entry;
                    break;
                }
            }
        }

        if (oEntry)
        {
            for (int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
            {
                if (oEntry->ItemId[j] <= 0)
                    continue;

                uint32 itemId = oEntry->ItemId[j];

                // just skip, reported in ObjectMgr::LoadItemTemplates
                ItemTemplate const* iProto = sObjectMgr->GetItemTemplate(itemId);
                if (!iProto)
                    continue;

                if (createInfo->OutfitId == 0)
                    continue;

                // BuyCount by default
                uint32 count = iProto->BuyCount;

                // @todo remove this, use data in dbc or player_createinfoitem.
                // special amount for food/drink
                if (iProto->Class == ITEM_CLASS_CONSUMABLE && iProto->SubClass == ITEM_SUBCLASS_FOOD_DRINK)
                {
                    switch (iProto->Spells[0].SpellCategory)
                    {
                        case SPELL_CATEGORY_FOOD:                                // food
                            count = getClass() == CLASS_DEATH_KNIGHT ? 10 : 4;
                            break;
                        case SPELL_CATEGORY_DRINK:                                // drink
                            count = 2;
                            break;
                    }
                    if (iProto->GetMaxStackSize() < count)
                        count = iProto->GetMaxStackSize();
                }

                switch(itemId)
                {
                    // This switch prevents these items (used next for a quest) to be added to a pandaren player at his creation.
                    case 73207:
                    case 73208:
                    case 73209:
                    case 73210:
                    case 73211:
                    case 73212:
                    case 73213:
                    case 76390:
                    case 76391:
                    case 76392:
                    case 76393:
                        continue;
                    default:
                        break;
                }

                StoreNewItemInBestSlots(itemId, count);
            }
        }
    }


    for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr != info->item.end(); ++item_id_itr)
        StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);

    // bags and main-hand weapon must equipped at this moment
    // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
    // or ammo not equipped in special bag
    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
        {
            uint16 eDest;
            // equip offhand weapon/shield if it attempt equipped before main-hand weapon
            InventoryResult msg = CanEquipItem(NULL_SLOT, eDest, pItem, false);
            if (msg == EQUIP_ERR_OK)
            {
                RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
                EquipItem(eDest, pItem, true);
            }
            // move other items to more appropriate slots
            else
            {
                ItemPosCountVec sDest;
                msg = CanStoreItem(NULL_BAG, NULL_SLOT, sDest, pItem, false);
                if (msg == EQUIP_ERR_OK)
                {
                    RemoveItem(INVENTORY_SLOT_BAG_0, i, true);
                    pItem = StoreItem(sDest, pItem, true); ///< pItem is never read 01/18/16
                }
            }
        }
    }
    // all item positions resolved

    // Pandaren's start quest
    if (createInfo->Race == RACE_PANDAREN_NEUTRAL)
    {
        Quest const* quest = NULL;
        switch (createInfo->Class)
        {
            case CLASS_WARRIOR: quest = sObjectMgr->GetQuestTemplate(30045); break;
            case CLASS_SHAMAN: quest = sObjectMgr->GetQuestTemplate(30044); break;
            case CLASS_ROGUE: quest = sObjectMgr->GetQuestTemplate(30043); break;
            case CLASS_PRIEST: quest = sObjectMgr->GetQuestTemplate(30042); break;
            case CLASS_HUNTER: quest = sObjectMgr->GetQuestTemplate(30041); break;
            case CLASS_MAGE: quest = sObjectMgr->GetQuestTemplate(30040); break;
            case CLASS_MONK: quest = sObjectMgr->GetQuestTemplate(30039); break;
            default: break;
        }

        if (quest)
        {
            this->AddQuest(quest, NULL);
            if (CanCompleteQuest(quest->GetQuestId()))
                CompleteQuest(quest->GetQuestId());
        }
    }

    if (WorldSession* l_Session = GetSession())
        l_Session->OnGMTicketGetTicketEvent();

    SetUInt32Value(EUnitFields::UNIT_FIELD_SCALE_DURATION, 500);
    return true;
}

bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount, ItemContext p_ItemContext)
{
    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: Creating initial item, itemId = %u, count = %u", titem_id, titem_amount);

    // attempt equip by one
    while (titem_amount > 0)
    {
        uint16 eDest;
        InventoryResult msg = CanEquipNewItem(NULL_SLOT, eDest, titem_id, false);
        if (msg != EQUIP_ERR_OK)
            break;

        Item* l_Item = EquipNewItem(eDest, titem_id, true);

        if (l_Item && p_ItemContext != ItemContext::None)
        {
            std::vector<uint32> l_Bonus;
            Item::GenerateItemBonus(titem_id, p_ItemContext, l_Bonus);
            l_Item->AddItemBonuses(l_Bonus);
        }

        AutoUnequipOffhandIfNeed();
        --titem_amount;
    }

    if (titem_amount == 0)
        return true;                                        // equipped

    // attempt store
    ItemPosCountVec sDest;
    // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
    InventoryResult msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount);
    if (msg == EQUIP_ERR_OK)
    {
        Item* l_Item = StoreNewItem(sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id));

        if (l_Item && p_ItemContext != ItemContext::None)
        {
            std::vector<uint32> l_Bonus;
            Item::GenerateItemBonus(titem_id, p_ItemContext, l_Bonus);
            l_Item->AddItemBonuses(l_Bonus);
        }

        return true;                                        // stored
    }

    // item can't be added
    sLog->outError(LOG_FILTER_PLAYER_ITEMS, "STORAGE: Can't equip or store initial item %u for race %u class %u, error msg = %u", titem_id, getRace(), getClass(), msg);
    return false;
}

void Player::RewardCurrencyAtKill(Unit* p_Victim)
{
    if (!p_Victim || p_Victim->IsPlayer())
        return;

    if (!p_Victim->ToCreature())
        return;

    if (!p_Victim->ToCreature()->GetEntry())
        return;

    if (uint32 l_TrackingQuestId = Vignette::GetTrackingQuestIdFromWorldObject(p_Victim))
    {
        uint32 l_QuestBit = GetQuestUniqueBitFlag(l_TrackingQuestId);
        if (IsQuestBitFlaged(l_QuestBit))
            return;
    }

    CurrencyOnKillEntry const* l_Curr = sObjectMgr->GetCurrencyOnKillEntry(p_Victim->ToCreature()->GetEntry());
    if (!l_Curr)
        return;

    bool l_Result = true;
    if (p_Victim->ToCreature()->AI())
        p_Victim->ToCreature()->AI()->CurrenciesRewarder(l_Result);

    if (!l_Result)
        return;

    for (CurrencyOnKillEntry::const_iterator idx = l_Curr->begin(); idx != l_Curr->end(); ++idx)
    {
        // Players won't receive justice points from pre-MoP dungeons/raids when they are more than Cataclysm max level (85)
        if ((idx->first == CURRENCY_TYPE_JUSTICE_POINTS
            || idx->first == CURRENCY_TYPE_VALOR_POINTS)
            && p_Victim->GetMap()->Expansion() != EXPANSION_MISTS_OF_PANDARIA
            && getLevel() > 85)
            continue;

        int32 l_Pct = 100;
        Unit::AuraEffectList const& l_Auras = GetAuraEffectsByType(SPELL_AURA_MOD_CURRENCY_GAIN_PCT);
        for (Unit::AuraEffectList::const_iterator i = l_Auras.begin(); i != l_Auras.end(); ++i)
        {
            if (idx->first == (*i)->GetMiscValue()) ///< Comparison of integers of different signs: 'const unsigned int' and 'int32' (aka 'int')
                l_Pct += (*i)->GetAmount();
        }

        ModifyCurrency(idx->first, CalculatePct(idx->second, l_Pct));
    }
}
void Player::SendMirrorTimer(MirrorTimerType p_Type, uint32 p_MaxValue, uint32 p_CurrValue, int32 p_Regen)
{
    if (int(p_MaxValue) == DISABLED_MIRROR_TIMER)
    {
        if (int(p_CurrValue) != DISABLED_MIRROR_TIMER)
            StopMirrorTimer(p_Type);
        return;
    }

    WorldPacket l_Data(SMSG_START_MIRROR_TIMER, (21));
    uint32 l_SpellID = 0;

    l_Data << uint32(p_Type);
    l_Data << p_CurrValue;
    l_Data << p_MaxValue;
    l_Data << uint32(p_Regen);
    l_Data << uint32(l_SpellID);
    l_Data.WriteBit(0);
    GetSession()->SendPacket(&l_Data);
}

void Player::StopMirrorTimer(MirrorTimerType Type)
{
    m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
    WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
    data << uint32(Type);
    GetSession()->SendPacket(&data);
}

bool Player::IsImmuneToEnvironmentalDamage()
{
    // check for GM and death state included in isAttackableByAOE
    return (!isTargetableForAttack(false));
}

uint32 Player::EnvironmentalDamage(EnviromentalDamage p_Type, uint32 p_Damage)
{
    if (IsImmuneToEnvironmentalDamage())
        return 0;

    // Absorb, resist some environmental damage type
    uint32 l_Absorb = 0;
    uint32 l_Resist = 0;

    if (p_Type == DAMAGE_LAVA)
        CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, p_Damage, &l_Absorb, &l_Resist);
    else if (p_Type == DAMAGE_SLIME)
        CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, p_Damage, &l_Absorb, &l_Resist);
    else if (p_Type == DAMAGE_FALL)
    {
        /// Handle falling damage disabling in some situations
        if (InstanceScript* l_InstanceScript = GetInstanceScript())
        {
            if (l_InstanceScript->IsPlayerImmuneToFallDamage(this))
                return 0;
        }

        /// Glyph of Falling Meteor - 56247
        if (getClass() == CLASS_WARLOCK && HasAura(109151) && HasAura(56247))
            AddPct(p_Damage, -95);

        // Percentage from SPELL_AURA_REDUCE_FALL_DAMAGE_PERCENT
        AuraEffectList const& mReduceFallDamagePct = GetAuraEffectsByType(SPELL_AURA_REDUCE_FALL_DAMAGE_PERCENT);
        for (AuraEffectList::const_iterator i = mReduceFallDamagePct.begin(); i != mReduceFallDamagePct.end(); ++i)
            AddPct(p_Damage, (*i)->GetAmount());
    }

    p_Damage -= l_Absorb + l_Resist;

    DealDamageMods(this, p_Damage, &l_Absorb);

    WorldPacket l_Data(SMSG_ENVIRONMENTAL_DAMAGE_LOG, (21));
    l_Data.appendPackGUID(GetGUID());
    l_Data << uint8(p_Type != DAMAGE_FALL_TO_VOID ? p_Type : DAMAGE_FALL);
    l_Data << uint32(p_Damage);
    l_Data << uint32(l_Absorb);
    l_Data << uint32(l_Resist);

    l_Data.WriteBit(false);               ///< HasPowerData
    l_Data.FlushBits();

    SendMessageToSet(&l_Data, true);

    uint32 l_FinalDamage = DealDamage(this, p_Damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);

    if (!isAlive())
    {
        if (p_Type == DAMAGE_FALL)                               ///< DealDamage not apply item durability loss at self damage
        {
            sLog->outDebug(LOG_FILTER_PLAYER, "We are fall to death, loosing 10 percents durability");

            DurabilityLossAll(0.10f, false);
            /// durability lost message
            SendDurabilityLoss(this, 10);
        }

        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, p_Type);
    }

    return l_FinalDamage;
}

int32 Player::getMaxTimer(MirrorTimerType timer)
{
    switch (timer)
    {
        case FATIGUE_TIMER:
            return MINUTE * IN_MILLISECONDS;
        case BREATH_TIMER:
        {
            if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= AccountTypes(sWorld->getIntConfig(CONFIG_DISABLE_BREATHING)))
                return DISABLED_MIRROR_TIMER;
            int32 UnderWaterTime = 3 * MINUTE * IN_MILLISECONDS;
            AuraEffectList const& mModWaterBreathing = GetAuraEffectsByType(SPELL_AURA_MOD_WATER_BREATHING);
            for (AuraEffectList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
                AddPct(UnderWaterTime, (*i)->GetAmount());
            return UnderWaterTime;
        }
        case FIRE_TIMER:
        {
            if (!isAlive())
                return DISABLED_MIRROR_TIMER;
            return 1 * IN_MILLISECONDS;
        }
        default:
            return 0;
    }
}

void Player::UpdateMirrorTimers()
{
    // Desync flags for update on next HandleDrowning
    if (m_MirrorTimerFlags)
        m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
}

void Player::HandleDrowning(uint32 time_diff)
{
    if (!m_MirrorTimerFlags)
        return;

    // In water
    if (m_MirrorTimerFlags & UNDERWATER_INWATER)
    {
        // Vash'jir zones
        if (m_zoneUpdateId == 4815 || m_zoneUpdateId == 4816 || m_zoneUpdateId == 5144 || m_zoneUpdateId == 5145|| m_zoneUpdateId == 5146)
            return;

        // Breath timer not activated - activate it
        if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
        {
            m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
            SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
        }
        else                                                              // If activated - do tick
        {
            m_MirrorTimer[BREATH_TIMER]-=time_diff;
            // Timer limit - need deal damage
            if (m_MirrorTimer[BREATH_TIMER] < 0)
            {
                m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILLISECONDS;
                // Calculate and deal damage
                // @TODO: Check this formula
                uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
                EnvironmentalDamage(DAMAGE_DROWNING, damage);
            }
            else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER))      // Update time in client if need
                SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
        }
    }
    else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER)        // Regen timer
    {
        int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
        // Need breath regen
        m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
        if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
            StopMirrorTimer(BREATH_TIMER);
        else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
            SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
    }

    // In dark water
    if ((m_MirrorTimerFlags & UNDERWARER_INDARKWATER) && !GetVehicle())
    {
        // Fatigue timer not activated - activate it
        if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
        {
            m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
            SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
        }
        else
        {
            m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
            // Timer limit - need deal damage or teleport ghost to graveyard
            if (m_MirrorTimer[FATIGUE_TIMER] < 0)
            {
                m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILLISECONDS;
                if (isAlive())                                              // Calculate and deal damage
                {
                    uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
                    EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
                }
                else if (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GHOST))         // Teleport ghost to graveyard
                    RepopAtGraveyard();
            }
            else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
                SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
        }
    }
    else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER)       // Regen timer
    {
        int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
        m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
        if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
            StopMirrorTimer(FATIGUE_TIMER);
        else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
            SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
    }

    if (m_MirrorTimerFlags & (UNDERWATER_INLAVA /*| UNDERWATER_INSLIME*/) && !(_lastLiquid && _lastLiquid->SpellId))
    {
        // Breath timer not activated - activate it
        if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
            m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
        else
        {
            m_MirrorTimer[FIRE_TIMER] -= time_diff;
            if (m_MirrorTimer[FIRE_TIMER] < 0)
            {
                m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILLISECONDS;
                // Calculate and deal damage
                // TODO: Check this formula
                uint32 damage = urand(600, 700);
                if (m_MirrorTimerFlags & UNDERWATER_INLAVA)
                    EnvironmentalDamage(DAMAGE_LAVA, damage);
                // need to skip Slime damage in Undercity,
                // maybe someone can find better way to handle environmental damage
                //else if (m_zoneUpdateId != 1497)
                //    EnvironmentalDamage(DAMAGE_SLIME, damage);
            }
        }
    }
    else
        m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;

    // Recheck timers flag
    m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
    for (uint8 i = 0; i< MAX_TIMERS; ++i)
        if (m_MirrorTimer[i] != DISABLED_MIRROR_TIMER)
        {
            m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
            break;
        }
    m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
}

///The player sobers by 1% every 9 seconds
void Player::HandleSobering()
{
    m_drunkTimer = 0;

    uint8 currentDrunkValue = GetDrunkValue();
    uint8 drunk = currentDrunkValue ? --currentDrunkValue : 0;
    SetDrunkValue(drunk);
}

DrunkenState Player::GetDrunkenstateByValue(uint8 value)
{
    if (value >= 90)
        return DRUNKEN_SMASHED;
    if (value >= 50)
        return DRUNKEN_DRUNK;
    if (value)
        return DRUNKEN_TIPSY;
    return DRUNKEN_SOBER;
}

void Player::SetDrunkValue(uint8 newDrunkValue, uint32 itemId /*= 0*/)
{
    bool isSobering = newDrunkValue < GetDrunkValue();
    uint32 oldDrunkenState = Player::GetDrunkenstateByValue(GetDrunkValue());
    if (newDrunkValue > 100)
        newDrunkValue = 100;

    // select drunk percent or total SPELL_AURA_MOD_FAKE_INEBRIATE amount, whichever is higher for visibility updates
    int32 drunkPercent = std::max<int32>(newDrunkValue, GetTotalAuraModifier(SPELL_AURA_MOD_FAKE_INEBRIATE));
    if (drunkPercent)
    {
        m_invisibilityDetect.AddFlag(INVISIBILITY_DRUNK);
        m_invisibilityDetect.SetValue(INVISIBILITY_DRUNK, drunkPercent);
    }
    else if (!HasAuraType(SPELL_AURA_MOD_FAKE_INEBRIATE) && !newDrunkValue)
        m_invisibilityDetect.DelFlag(INVISIBILITY_DRUNK);

    uint32 newDrunkenState = Player::GetDrunkenstateByValue(newDrunkValue);
    SetByteValue(PLAYER_FIELD_ARENA_FACTION, PLAYER_BYTES_3_OFFSET_INEBRIATION, newDrunkValue);
    UpdateObjectVisibility();

    if (!isSobering)
        m_drunkTimer = 0;   // reset sobering timer

    if (newDrunkenState == oldDrunkenState)
        return;

    WorldPacket l_Data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
    l_Data.appendPackGUID(GetGUID());
    l_Data << uint32(itemId);
    l_Data << uint32(newDrunkenState);
    SendMessageToSet(&l_Data, true);
}

void Player::Update(uint32 p_time)
{
    if (!IsInWorld())
        return;

    //sAnticheatMgr->HandleHackDetectionTimer(this, p_time);
    if (!m_initializeCallback)
    {
        PreparedStatement* stmt;

        stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PET_BY_ENTRY_AND_SLOT);
        stmt->setUInt32(0, GetGUIDLow());
        stmt->setUInt32(1, m_currentPetSlot);
        _petPreloadCallback = CharacterDatabase.AsyncQuery(stmt);

        m_initializeCallback = true;
    }

    // Process player callback
    {
        PreparedQueryResult result;

        if (_petPreloadCallback.ready())
        {
            _petPreloadCallback.get(result);
            LoadPet(result);
            _petPreloadCallback.cancel();
        }

        if (_petLoginCallback.ready())
        {
            SQLQueryHolder* param;
            _petLoginCallback.get(param);

            Pet* pet = new Pet(this);
            pet->LoadPetFromDB(this, 0, 0, true, PET_SLOT_ACTUAL_PET_SLOT, false, (PetQueryHolder*)param, [param](Pet* p_Pet, bool p_Result) -> void
            {
                if (!p_Result)
                    delete p_Pet;

                delete param;
            });

            _petLoginCallback.cancel();
        }
    }

    // Zone Skip Update
    if ((sObjectMgr->IsSkipZoneEnabled() && sObjectMgr->IsSkipZone(GetZoneId())) || isAFK())
    {
        _skipCount++;
        _skipDiff += p_time;

        if (_skipCount < sObjectMgr->GetSkipUpdateCount())
            return;

        p_time = _skipDiff;
        _skipCount = 0;
        _skipDiff = 0;
    }

    if (m_InCinematic && m_CinematicSequence)
    {
        bool l_StartedAtClient = getMSTime() > m_CinematicClientStartTime;
        uint32 l_Time = getMSTime() - m_CinematicClientStartTime;

        if (l_StartedAtClient)
        {
            if (l_Time > m_CinematicSequence->Duration)
                StopCinematic();
            else if (l_StartedAtClient)
            {
                Position l_NewPosition;
                m_CinematicSequence->GetPositionAtTime(l_Time, &l_NewPosition.m_positionX, &l_NewPosition.m_positionY, &l_NewPosition.m_positionZ);

                Unit::UpdatePosition(l_NewPosition.m_positionX, l_NewPosition.m_positionY, l_NewPosition.m_positionZ, 0, true);
                SetFall(false);
            }
        }
    }

    // undelivered mail
    if (m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
    {
        SendNewMail();
        ++unReadMails;

        // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
        m_nextMailDelivereTime = 0;
    }

    // If this is set during update SetSpellModTakingSpell call is missing somewhere in the code
    // Having this would prevent more aura charges to be dropped, so let's crash
    //ASSERT (!m_spellModTakingSpell);
    if (m_spellModTakingSpell)
    {
        //sLog->outFatal(LOG_FILTER_PLAYER, "Player has m_pad %u during update!", m_pad);
        //if (m_spellModTakingSpell)
        sLog->outFatal(LOG_FILTER_SPELLS_AURAS, "Player has m_spellModTakingSpell %u during update!", m_spellModTakingSpell->m_spellInfo->Id);
        m_spellModTakingSpell = NULL;
    }

    //used to implement delayed far teleports
    SetCanDelayTeleport(true);
    Unit::Update(p_time);
    SetCanDelayTeleport(false);

    time_t now = time(nullptr);

    if (m_WargameRequest != nullptr && (m_WargameRequest->CreationDate + 60) < now)
    {
        delete m_WargameRequest;
        m_WargameRequest = nullptr;
    }

    UpdatePvPFlag(now);

    UpdateContestedPvP(p_time);

    UpdateDuelFlag(now);

    CheckDuelDistance(now);

    UpdateAfkReport(now);

    UpdatePvP(p_time);

    if (isCharmed())
        if (Unit* charmer = GetCharmer())
            if (charmer->GetTypeId() == TYPEID_UNIT && charmer->isAlive())
                UpdateCharmedAI();

    // Update items that have just a limited lifetime
    if (now > m_Last_tick)
        UpdateItemDuration(uint32(now - m_Last_tick));

    // check every second
    if (now > m_Last_tick + 1000)
        UpdateSoulboundTradeItems();

    if (_petBattleJournalCallback.ready())
    {
        PreparedQueryResult l_Result;
        _petBattleJournalCallback.get(l_Result);
        bool l_ResultRes = _LoadPetBattles(std::move(l_Result));
        _petBattleJournalCallback.cancel();

        if (!l_ResultRes)
            ReloadPetBattles();
    }

    if (!m_timedquests.empty())
    {
        QuestSet::iterator iter = m_timedquests.begin();
        while (iter != m_timedquests.end())
        {
            QuestStatusData& q_status = m_QuestStatus[*iter];
            if (q_status.Timer <= p_time)
            {
                uint32 quest_id  = *iter;
                ++iter;                                     // current iter will be removed in FailQuest
                FailQuest(quest_id);
            }
            else
            {
                q_status.Timer -= p_time;
                m_QuestStatusSave[*iter] = true;
                ++iter;
            }
        }
    }

    GetAchievementMgr().UpdateTimedAchievements(p_time);

    if (HasUnitState(UNIT_STATE_MELEE_ATTACKING) && !HasUnitState(UNIT_STATE_CASTING))
    {
        if (Unit* victim = getVictim())
        {
            // default combat reach 10
            // TODO add weapon, skill check

            bool l_MustCheckO = true;

            /// Can attack own vehicle in any direction
            if (m_vehicle)
            {
                if (IsOnVehicle(victim) || (m_vehicle->GetBase() && m_vehicle->GetBase()->IsOnVehicle(victim)))
                    l_MustCheckO = false;
            }

            if (isAttackReady(WeaponAttackType::BaseAttack))
            {
                if (!IsWithinMeleeRange(victim) && !HasAuraType(SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL))
                {
                    setAttackTimer(WeaponAttackType::BaseAttack, 100);
                    if (m_swingErrorMsg != 1)               // send single time (client auto repeat)
                    {
                        SendAttackSwingError(ATTACKSWINGERR_NOT_IN_RANGE);
                        m_swingErrorMsg = 1;
                    }
                }
                //120 degrees of radiant range
                else if (l_MustCheckO && !HasInArc(2 * M_PI / 3, victim))
                {
                    setAttackTimer(WeaponAttackType::BaseAttack, 100);
                    if (m_swingErrorMsg != 2)               // send single time (client auto repeat)
                    {
                        SendAttackSwingError(ATTACKSWINGERR_BAD_FACING);
                        m_swingErrorMsg = 2;
                    }
                }
                else
                {
                    m_swingErrorMsg = 0;                    // reset swing error state

                    // prevent base and off attack in same time, delay attack at 0.2 sec
                    if (haveOffhandWeapon())
                        if (getAttackTimer(WeaponAttackType::OffAttack) < ATTACK_DISPLAY_DELAY)
                            setAttackTimer(WeaponAttackType::OffAttack, ATTACK_DISPLAY_DELAY);

                    // do attack if player doesn't have Shadow Blades or SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL
                    if (!HasAura(121471) && !HasAuraType(SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL))
                    {
                        AttackerStateUpdate(victim, WeaponAttackType::BaseAttack);
                        resetAttackTimer(WeaponAttackType::BaseAttack);
                    }
                    else if (HasAuraType(SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL) && IsWithinLOSInMap(victim))
                    {
                        if (HasUnitState(UNIT_STATE_CANNOT_AUTOATTACK) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
                            return;

                        // Should have only one aura of this type at the same time
                        AuraEffectList const& mOverrideAutoAttacks = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL);
                        for (AuraEffectList::const_iterator i = mOverrideAutoAttacks.begin(); i != mOverrideAutoAttacks.end(); ++i)
                        {
                            CastSpell(victim, (*i)->GetTriggerSpell(), true);
                            resetAttackTimer(WeaponAttackType::BaseAttack);
                            break;
                        }
                    }
                    // Shadow Blade - Main Hand
                    else if (getClass() == CLASS_ROGUE && HasAura(121471) && !HasAura(137586) && IsWithinLOSInMap(victim))
                    {
                        if (HasUnitState(UNIT_STATE_CANNOT_AUTOATTACK) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
                            return;

                        CastSpell(victim, 121473, true);
                        resetAttackTimer(WeaponAttackType::BaseAttack);
                    }
                    else if (getClass() == CLASS_ROGUE && HasAura(137586) && HasAura(121471) && IsWithinLOSInMap(victim))
                    {
                        if (HasUnitState(UNIT_STATE_CANNOT_AUTOATTACK) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
                            return;

                        CastSpell(victim, 140308, true); // Shadow Shuriken Toss
                        resetAttackTimer(WeaponAttackType::BaseAttack);
                    }
                }
            }

            if (haveOffhandWeapon() && isAttackReady(WeaponAttackType::OffAttack))
            {
                if (!IsWithinMeleeRange(victim) && !HasAuraType(SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL))
                    setAttackTimer(WeaponAttackType::OffAttack, 100);
                else if (l_MustCheckO && !HasInArc(2 * M_PI / 3, victim))
                    setAttackTimer(WeaponAttackType::OffAttack, 100);
                else
                {
                    // prevent base and off attack in same time, delay attack at 0.2 sec
                    if (getAttackTimer(WeaponAttackType::BaseAttack) < ATTACK_DISPLAY_DELAY)
                        setAttackTimer(WeaponAttackType::BaseAttack, ATTACK_DISPLAY_DELAY);

                    // do attack if player doesn't have Shadow Blades or SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL
                    if (!HasAuraType(SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL))
                    {
                        AttackerStateUpdate(victim, WeaponAttackType::OffAttack);
                        resetAttackTimer(WeaponAttackType::OffAttack);
                    }
                    else if (HasAuraType(SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL) && IsWithinLOSInMap(victim))
                    {
                        if (HasUnitState(UNIT_STATE_CANNOT_AUTOATTACK) || HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
                            return;

                        // Should have only one aura of this type at the same time
                        AuraEffectList const& mOverrideAutoAttacks = GetAuraEffectsByType(SPELL_AURA_OVERRIDE_AUTO_ATTACKS_BY_SPELL);
                        for (AuraEffectList::const_iterator i = mOverrideAutoAttacks.begin(); i != mOverrideAutoAttacks.end(); ++i)
                        {
                            CastSpell(victim, (*i)->GetMiscValue(), true);
                            resetAttackTimer(WeaponAttackType::OffAttack);
                            break;
                        }
                    }
                }
            }
        }
    }

    if (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
    {
        if (roll_chance_i(3) && GetTimeInnEnter() > 0)      // freeze update
        {
            time_t time_inn = time(NULL)-GetTimeInnEnter();
            if (time_inn >= 10)                             // freeze update
            {
                float bubble = 0.125f*sWorld->getRate(RATE_REST_INGAME);
                                                            // speed collect rest bonus (section/in hour)
                SetRestBonus(GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_FIELD_NEXT_LEVEL_XP)/72000)*bubble);
                UpdateInnerTime(time(NULL));
            }
        }
    }

    if (m_weaponChangeTimer > 0)
    {
        if (p_time >= m_weaponChangeTimer)
            m_weaponChangeTimer = 0;
        else
            m_weaponChangeTimer -= p_time;
    }

    if (m_zoneUpdateTimer > 0)
    {
        if (p_time >= m_zoneUpdateTimer)
        {
            uint32 newzone, newarea;
            GetZoneAndAreaId(newzone, newarea, true);

            if (m_zoneUpdateId != newzone)
                UpdateZone(newzone, newarea);                // also update area
            else
            {
                // use area updates as well
                // needed for free far all arenas for example
                if (m_areaUpdateId != newarea)
                    UpdateArea(newarea);

                m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
            }

            /// Shipyard map has broken area settings
            if (IsInShipyard())
            {
                uint64 l_Guid = GetGUID();
                Map * l_Map = sMapMgr->FindBaseNonInstanceMap(MS::Garrison::Globals::BaseMap);

                if (!l_Map)
                    l_Map = sMapMgr->CreateBaseMap(MS::Garrison::Globals::BaseMap);

                if (l_Map)
                {
                    uint32 l_DraenorBaseMap_Zone, l_DraenorBaseMap_Area;

                    l_Map->GetZoneAndAreaId(l_DraenorBaseMap_Zone, l_DraenorBaseMap_Area, m_positionX, m_positionY, m_positionZ);
                    const GarrSiteLevelEntry * l_GarrisonSiteEntry = m_Garrison->GetGarrisonSiteLevelEntry(); ///< l_garrisonSiteEntry is never read 01/18/16<--- Variable 'l_GarrisonSiteEntry' is assigned a value that is never used.

                    if (l_DraenorBaseMap_Area != MS::Garrison::gGarrisonShipyardAreaID[m_Garrison->GetGarrisonFactionIndex()])
                    {
                        sMapMgr->AddCriticalOperation([l_Guid]() -> bool
                        {
                            Player * l_Player = sObjectAccessor->FindPlayer(l_Guid);

                            if (l_Player && l_Player->IsInWorld())
                            {
                                l_Player->_SetOutOfShipyard();
                                return true;
                            }

                            return false;
                        });
                    }
                }
            }
        }
        else
            m_zoneUpdateTimer -= p_time;
    }

    if (m_timeSyncTimer > 0)
    {
        if (p_time >= m_timeSyncTimer)
            SendTimeSync();
        else
            m_timeSyncTimer -= p_time;
    }

    if (isAlive())
    {
        m_RegenPowerTimer += p_time;
        RegenerateAll();
    }

    if (m_deathState == JUST_DIED)
        KillPlayer();

    if (m_nextSave > 0)
    {
        if (p_time >= m_nextSave)
        {
            // m_nextSave reseted in SaveToDB call
            SaveToDB();
            sLog->outDebug(LOG_FILTER_PLAYER, "Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
        }
        else
            m_nextSave -= p_time;
    }

    //Handle Water/drowning
    HandleDrowning(p_time);

    // Played time
    if (now > m_Last_tick)
    {
        uint32 elapsed = uint32(now - m_Last_tick);
        m_Played_time[PLAYED_TIME_TOTAL] += elapsed;        // Total played time
        m_Played_time[PLAYED_TIME_LEVEL] += elapsed;        // Level played time
        m_Last_tick = now;
    }

    if (GetDrunkValue())
    {
        m_drunkTimer += p_time;
        if (m_drunkTimer > 9 * IN_MILLISECONDS)
            HandleSobering();
    }

    if (HasPendingBind())
    {
        if (_pendingBindTimer <= p_time)
        {
            // Player left the instance
            if (_pendingBindId == GetInstanceId())
                BindToInstance();
            SetPendingBind(0, 0);
        }
        else
            _pendingBindTimer -= p_time;
    }

    // not auto-free ghost from body in instances
    if (m_deathTimer > 0 && !GetBaseMap()->Instanceable() && !HasAuraType(SPELL_AURA_PREVENT_RESURRECTION))
    {
        if (p_time >= m_deathTimer)
        {
            m_deathTimer = 0;
            BuildPlayerRepop();
            RepopAtGraveyard();
        }
        else
            m_deathTimer -= p_time;
    }

    if (m_knockBackTimer)
    {
        if ( m_knockBackTimer + 2000 < getMSTime())
            m_knockBackTimer = 0;
    }

    UpdateEnchantTime(p_time);
    UpdateHomebindTime(p_time);

    if (!_instanceResetTimes.empty())
    {
        for (InstanceTimeMap::iterator itr = _instanceResetTimes.begin(); itr != _instanceResetTimes.end();)
        {
            if (itr->second < now)
                _instanceResetTimes.erase(itr++);
            else
                ++itr;
        }
    }

    // group update
    // Avoid spam of SMSG_PARTY_MEMBER_STAT
    if (m_groupUpdateDelay < p_time)
    {
        SendUpdateToOutOfRangeGroupMembers();
        m_groupUpdateDelay = 5000;
    }
    else
        m_groupUpdateDelay -= p_time;

    Pet* pet = GetPet();
    if (pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityRange()) && !pet->isPossessed())
        RemovePet(pet, PET_SLOT_ACTUAL_PET_SLOT, true, pet->m_Stampeded);

    if (pet && IsFlying() && !pet->isPossessed())
    {
        UnsummonPetTemporaryIfAny();
        m_needSummonPetAfterStopFlying = true;
    }
    else if (!IsFlying() && m_needSummonPetAfterStopFlying)
    {
        ResummonPetTemporaryUnSummonedIfAny();
        m_needSummonPetAfterStopFlying = false;
    }

    //we should execute delayed teleports only for alive(!) players
    //because we don't want player's ghost teleported from graveyard
    if (IsHasDelayedTeleport())
        TeleportTo(m_teleport_dest, m_teleport_options);

    m_GarrisonUpdateTimer.Update(p_time);

    if (m_GarrisonUpdateTimer.Passed())
    {
        if (m_Garrison)
            m_Garrison->Update();

        m_GarrisonUpdateTimer.Reset();
    }

    m_VignetteMgr.Update();

    sScriptMgr->OnPlayerUpdate(this, p_time);

    m_CriticalOperationLock.acquire();

    std::queue<std::function<bool()>> l_CriticalOperationFallBack;
    while (!m_CriticalOperation.empty())
    {
        if (m_CriticalOperation.front())
        {
            if (!(m_CriticalOperation.front()()))
                l_CriticalOperationFallBack.push(m_CriticalOperation.front());
        }

        m_CriticalOperation.pop();
    }

    while (!l_CriticalOperationFallBack.empty())
    {
        m_CriticalOperation.push(l_CriticalOperationFallBack.front());
        l_CriticalOperationFallBack.pop();
    }

    m_CriticalOperationLock.release();
}

void Player::setDeathState(DeathState s)
{
    uint32 ressSpellId = 0;

    bool cur = isAlive();

    if (s == JUST_DIED)
    {
        if (!cur)
        {
            sLog->outError(LOG_FILTER_PLAYER, "setDeathState: attempt to kill a dead player %s(%d)", GetName(), GetGUIDLow());
            return;
        }

        // drunken state is cleared on death
        SetDrunkValue(0);

        ClearResurrectRequestData();

        if (Pet* pet = GetPet())
            RemovePet(pet, PET_SLOT_ACTUAL_PET_SLOT, true, pet->m_Stampeded);
        else
            RemovePet(NULL, PET_SLOT_ACTUAL_PET_SLOT, true, GetPet() ? GetPet()->m_Stampeded : true);

        // save value before aura remove in Unit::setDeathState
        ressSpellId = GetUInt32Value(PLAYER_FIELD_SELF_RES_SPELL);

        // passive spell
        if (!ressSpellId)
            ressSpellId = GetResurrectionSpellId();
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
        GetAchievementMgr().ResetAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE, ACHIEVEMENT_CRITERIA_CONDITION_NO_DEATH);
        GetAchievementMgr().ResetAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL, ACHIEVEMENT_CRITERIA_CONDITION_NO_DEATH);
        GetAchievementMgr().ResetAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS, ACHIEVEMENT_CRITERIA_CONDITION_NO_DEATH);
    }
    else if (s == ALIVE)
    {
        if (HasAura(84559))
            RemoveAurasDueToSpell(84559); // The Quick and the Dead
    }

    Unit::setDeathState(s);

    // restore resurrection spell id for player after aura remove
    if (s == JUST_DIED && cur && ressSpellId)
        SetUInt32Value(PLAYER_FIELD_SELF_RES_SPELL, ressSpellId);

    if (isAlive() && !cur)
        //clear aura case after resurrection by another way (spells will be applied before next death)
        SetUInt32Value(PLAYER_FIELD_SELF_RES_SPELL, 0);
}

bool Player::BuildEnumData(PreparedQueryResult p_Result, ByteBuffer* p_Data)
{
    //             0               1                2                3                 4                  5                       6                        7
    //    "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
    //     8                9               10                     11                     12                     13                    14
    //    "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
    //    15                    16                   17                     18                   19               20                     21               22
    //    "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_banned.guid, characters.slot, character_declinedname.genitive"

    Field * l_Fields = p_Result->Fetch();

    /// Character visual
    uint8 l_CharacterRace       = l_Fields[2].GetUInt8();
    uint8 l_CharacterClass      = l_Fields[3].GetUInt8();
    uint8 l_CharacterGender     = l_Fields[4].GetUInt8();
    uint8 l_CharacterSkin       = uint8( l_Fields[5].GetUInt32() & 0xFF);
    uint8 l_CharacterFace       = uint8((l_Fields[5].GetUInt32() >> 8)  & 0xFF);
    uint8 l_CharacterHairStyle  = uint8((l_Fields[5].GetUInt32() >> 16) & 0xFF);
    uint8 l_CharacterHairColor  = uint8((l_Fields[5].GetUInt32() >> 24) & 0xFF);
    uint8 l_CharacterFacialHair = uint8( l_Fields[6].GetUInt32() & 0xFF);

    /// Character informations
    uint64      l_CharacterGuid         = MAKE_NEW_GUID(l_Fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
    std::string l_CharacterName         = l_Fields[1].GetString();
    uint32      l_CharacterLoginFlags   = l_Fields[15].GetUInt16();
    uint32      l_CharacterGuildID      = l_Fields[13].GetUInt32();
    uint8       l_CharacterOrder        = l_Fields[21].GetUInt8();
    uint8       l_CharacterLevel        = l_Fields[7].GetUInt8();
    uint64      l_CharacterGuildGuid    = MAKE_NEW_GUID(l_CharacterGuildID, 0, l_CharacterGuildID ? uint32(HIGHGUID_GUILD) : 0);
    Tokenizer   l_CharacterEquipment(l_Fields[19].GetString(), ' ');

    /// Character location
    uint32  l_CharacterZoneID       = l_Fields[8].GetUInt16();
    uint32  l_CharacterMapID        = uint32(l_Fields[9].GetUInt16());
    float   l_CharacterPositionX    = l_Fields[10].GetFloat();
    float   l_CharacterPositionY    = l_Fields[11].GetFloat();
    float   l_CharacterPositionZ    = l_Fields[12].GetFloat();

    uint32 l_PlayerFlags = l_Fields[14].GetUInt32();
    uint32 l_CharacterFlags = 0;

    if (l_PlayerFlags & PLAYER_FLAGS_HIDE_HELM)
        l_CharacterFlags |= CHARACTER_FLAG_HIDE_HELM;

    if (l_PlayerFlags & PLAYER_FLAGS_HIDE_CLOAK)
        l_CharacterFlags |= CHARACTER_FLAG_HIDE_CLOAK;

    if (l_PlayerFlags & PLAYER_FLAGS_GHOST)
        l_CharacterFlags |= CHARACTER_FLAG_GHOST;

    if (l_CharacterLoginFlags & AT_LOGIN_RENAME)
        l_CharacterFlags |= CHARACTER_FLAG_RENAME;

    if (l_Fields[20].GetUInt32())
        l_CharacterFlags |= CHARACTER_FLAG_LOCKED_BY_BILLING;

    if (sWorld->getBoolConfig(CONFIG_DECLINED_NAMES_USED))
    {
        if (!l_Fields[22].GetString().empty())
            l_CharacterFlags |= CHARACTER_FLAG_DECLINED;
    }
    else
        l_CharacterFlags |= CHARACTER_FLAG_DECLINED;

    if (l_CharacterLoginFlags & AT_LOGIN_LOCKED_FOR_TRANSFER)
        l_CharacterFlags |= CHARACTER_LOCKED_FOR_TRANSFER;

    bool l_CharacterFirstLogin = l_CharacterLoginFlags & AT_LOGIN_FIRST;

    uint32 l_CharacterCustomizationFlags = 0;

    if (l_CharacterLoginFlags & AT_LOGIN_CUSTOMIZE)
        l_CharacterCustomizationFlags = CHAR_CUSTOMIZE_FLAG_CUSTOMIZE;
    else if (l_CharacterLoginFlags & AT_LOGIN_CHANGE_FACTION)
        l_CharacterCustomizationFlags = CHAR_CUSTOMIZE_FLAG_FACTION;
    else if (l_CharacterLoginFlags & AT_LOGIN_CHANGE_RACE)
        l_CharacterCustomizationFlags = CHAR_CUSTOMIZE_FLAG_RACE;

    uint32 l_CharacterPetDisplayId  = 0;
    uint32 l_CharacterPetLevel      = 0;
    uint32 l_CharacterPetFamily     = 0;

    /// show pet at selection character in character list only for non-ghost character
    if (p_Result && !(l_PlayerFlags & PLAYER_FLAGS_GHOST) && (l_CharacterClass == CLASS_WARLOCK || l_CharacterClass == CLASS_HUNTER || l_CharacterClass == CLASS_DEATH_KNIGHT))
    {
        uint32 l_PetEntry = l_Fields[16].GetUInt32();

        if (CreatureTemplate const* l_CreatureTemplate = sObjectMgr->GetCreatureTemplate(l_PetEntry))
        {
            l_CharacterPetDisplayId = l_Fields[17].GetUInt32();
            l_CharacterPetLevel     = l_Fields[18].GetUInt16();
            l_CharacterPetFamily    = l_CreatureTemplate->family;
        }
    }

    p_Data->appendPackGUID(l_CharacterGuid);                ///< Character GUID
    *p_Data << uint8(l_CharacterOrder);                     ///< List order
    *p_Data << uint8(l_CharacterRace);                      ///< Race
    *p_Data << uint8(l_CharacterClass);                     ///< Class
    *p_Data << uint8(l_CharacterGender);                    ///< Gender
    *p_Data << uint8(l_CharacterSkin);                      ///< Skin
    *p_Data << uint8(l_CharacterFace);                      ///< Face
    *p_Data << uint8(l_CharacterHairStyle);                 ///< Hair style
    *p_Data << uint8(l_CharacterHairColor);                 ///< Hair color
    *p_Data << uint8(l_CharacterFacialHair);                ///< Facial hair
    *p_Data << uint8(l_CharacterLevel);                     ///< Level
    *p_Data << uint32(l_CharacterZoneID);                   ///< Zone id
    *p_Data << uint32(l_CharacterMapID);                    ///< Map Id
    *p_Data << float(l_CharacterPositionX);                 ///< X
    *p_Data << float(l_CharacterPositionY);                 ///< Y
    *p_Data << float(l_CharacterPositionZ);                 ///< Z
    p_Data->appendPackGUID(l_CharacterGuildGuid);           ///< Character guild GUID
    *p_Data << uint32(l_CharacterFlags);                    ///< Character flags
    *p_Data << uint32(l_CharacterCustomizationFlags);       ///< atLoginFlags
    *p_Data << uint32(0);                                   ///< Character Boost
    *p_Data << uint32(l_CharacterPetDisplayId);             ///< Pet DisplayID
    *p_Data << uint32(l_CharacterPetLevel);                 ///< Pet level
    *p_Data << uint32(l_CharacterPetFamily);                ///< Pet family
    *p_Data << uint32(0);                                   ///< Profession 1
    *p_Data << uint32(0);                                   ///< Profession 2

    /// Character visible equipment
    for (uint8 l_EquipmentSlot = 0; l_EquipmentSlot < INVENTORY_SLOT_BAG_END; ++l_EquipmentSlot)
    {
        uint32 l_Visualbase = l_EquipmentSlot * 3;
        uint64 l_ItemDatas  = GetUInt64ValueFromArray(l_CharacterEquipment, l_Visualbase);
        uint32 l_ItemID     = ((uint32*)(&l_ItemDatas))[0];
        uint32 l_DisplayID  = ((uint32*)(&l_ItemDatas))[1];

        ItemTemplate const* l_ItemTemplate = sObjectMgr->GetItemTemplate(l_ItemID);
        if (!l_ItemTemplate)
        {
            *p_Data << uint32(0);                           ///< Item display ID
            *p_Data << uint32(0);                           ///< Enchantment aura ID
            *p_Data << uint8(0);                            ///< Inventory type

            continue;
        }

        SpellItemEnchantmentEntry const* l_ItemEnchantmentEntry = nullptr;

        uint32 l_EnchantmentData = GetUInt32ValueFromArray(l_CharacterEquipment, l_Visualbase + 1);

        for (uint8 l_EnchantmentSlot = PERM_ENCHANTMENT_SLOT; l_EnchantmentSlot <= TEMP_ENCHANTMENT_SLOT; ++l_EnchantmentSlot)
        {
            /// Values stored in 2 uint16
            uint32 l_EnchantmentID = 0x0000FFFF & (l_EnchantmentData >> l_EnchantmentSlot * 16);

            if (!l_EnchantmentID)
                continue;

            l_ItemEnchantmentEntry = sSpellItemEnchantmentStore.LookupEntry(l_EnchantmentID);

            if (l_ItemEnchantmentEntry)
                break;
        }

        *p_Data << uint32(l_DisplayID ? l_DisplayID : l_ItemTemplate->DisplayInfoID);       ///< Item display ID
        *p_Data << uint32(l_ItemEnchantmentEntry ? l_ItemEnchantmentEntry->itemVisualID : 0);    ///< Enchantment aura ID
        *p_Data << uint8(l_ItemTemplate->InventoryType);                                    ///< Inventory type
    }

    p_Data->WriteBits(l_CharacterName.size(), 6);           ///< Character name
    p_Data->WriteBit(l_CharacterFirstLogin);                ///< Is character first login
    p_Data->WriteBit(0);                                    ///< Boosted to level 90
    p_Data->WriteBits(0, 5);                                ///< Unk 19508
    p_Data->FlushBits();
    p_Data->WriteString(l_CharacterName);                   ///< Character name

    return true;
}

bool Player::ToggleAFK()
{
    ToggleFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_AFK);

    bool state = HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_AFK);

    // afk player not allowed in battleground
    if (state && InBattleground() && !InArena())
        LeaveBattleground();

    return state;
}

bool Player::ToggleDND()
{
    ToggleFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_DND);

    return HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_DND);
}

uint8 Player::GetChatTag() const
{
    uint8 tag = CHAT_TAG_NONE;

    if (isGMChat())
        tag |= CHAT_TAG_GM;
    if (isDND())
        tag |= CHAT_TAG_DND;
    if (isAFK())
        tag |= CHAT_TAG_AFK;
    if (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_DEVELOPER))
        tag |= CHAT_TAG_DEV;

    return tag;
}

bool Player::TeleportTo(uint32 p_MapID, float p_X, float p_Y, float p_Z, float p_O, uint32 p_Options)
{
    if (!MapManager::IsValidMapCoord(p_MapID, p_X, p_Y, p_Z, p_O))
    {
        sLog->outError(LogFilterType::LOG_FILTER_MAPS, "TeleportTo: invalid map (%d) or invalid coordinates (X: %f, Y: %f, Z: %f, O: %f) given when teleporting player (GUID: %u, name: %s, map: %d, X: %f, Y: %f, Z: %f, O: %f).",
            p_MapID, p_X, p_Y, p_Z, p_O, GetGUIDLow(), GetName(), GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
        return false;
    }

    if (AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()) && DisableMgr::IsDisabledFor(DisableType::DISABLE_TYPE_MAP, p_MapID, this))
    {
        sLog->outError(LogFilterType::LOG_FILTER_MAPS, "Player (GUID: %u, name: %s) tried to enter a forbidden map %u", GetGUIDLow(), GetName(), p_MapID);
        SendTransferAborted(p_MapID, TRANSFER_ABORT_MAP_NOT_ALLOWED);
        return false;
    }

    /// Preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
    Pet* l_Pet = GetPet();

    MapEntry const* l_MapEntry = sMapStore.LookupEntry(p_MapID);

    /// Don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
    /// Don't let gm level > 1 either
    if (!InBattleground() && l_MapEntry->IsBattlegroundOrArena())
        return false;

    /// Client without expansion support
    if (GetSession()->Expansion() < l_MapEntry->Expansion())
    {
        sLog->outDebug(LogFilterType::LOG_FILTER_MAPS, "Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), p_MapID);

        if (GetTransport())
        {
            m_transport->RemovePassenger(this);
            m_transport = nullptr;
            m_movementInfo.t_pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f);
            m_movementInfo.t_time = 0;
            m_movementInfo.t_seat = -1;

            /// Teleport to near graveyard if on transport, looks blizz like :)
            RepopAtGraveyard();
        }

        SendTransferAborted(p_MapID, TRANSFER_ABORT_INSUF_EXPAN_LVL, l_MapEntry->Expansion());
        /// Normal client can't teleport to this map...
        return false;
    }
    else
        sLog->outDebug(LogFilterType::LOG_FILTER_MAPS, "Player %s is being teleported to map %u", GetName(), p_MapID);

    if (m_vehicle)
        ExitVehicle();

    /// Reset movement flags at teleport, because player will continue move with these flags after teleport
    SetUnitMovementFlags(GetUnitMovementFlags() & MOVEMENTFLAG_MASK_HAS_PLAYER_STATUS_OPCODE);
    m_movementInfo.ResetJump();
    DisableSpline();

    if (m_transport)
    {
        if (!(p_Options & TeleportToOptions::TELE_TO_NOT_LEAVE_TRANSPORT))
        {
            m_transport->RemovePassenger(this);
            m_transport = nullptr;
            m_movementInfo.t_pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f);
            m_movementInfo.t_time = 0;
            m_movementInfo.t_seat = -1;
            m_movementInfo.t_guid = 0;
        }
    }

    /// The player was ported to another map and loses the duel immediately.
    /// We have to perform this check before the teleport, otherwise the
    /// ObjectAccessor won't find the flag.
    if (m_Duel && GetMapId() != p_MapID && GetMap()->GetGameObject(GetGuidValue(EPlayerFields::PLAYER_FIELD_DUEL_ARBITER)))
        DuelComplete(DuelCompleteType::DUEL_FLED);

    /// Save previous location
    m_PreviousLocationMapId = GetMapId();
    m_PreviousLocationX     = GetPositionX();
    m_PreviousLocationY     = GetPositionY();
    m_PreviousLocationZ     = GetPositionZ();
    m_PreviousLocationO     = GetOrientation();

    if (GetMapId() == p_MapID)
    {
        /// Lets reset far teleport flag if it wasn't reset during chained teleports
        SetSemaphoreTeleportFar(false);
        /// Setup delayed teleport flag
        SetDelayedTeleportFlag(IsCanDelayTeleport());
        /// If teleport spell is casted in Unit::Update() func
        /// Then we need to delay it until update process will be finished
        if (IsHasDelayedTeleport())
        {
            SetSemaphoreTeleportNear(true);
            /// Lets save teleport destination for player
            m_teleport_dest = WorldLocation(p_MapID, p_X, p_Y, p_Z, p_O);
            m_teleport_options = p_Options;
            return true;
        }

        if (!(p_Options & TeleportToOptions::TELE_TO_NOT_UNSUMMON_PET))
        {
            /// Same map, only remove pet if out of range for new position
            if (l_Pet && !l_Pet->IsWithinDist3d(p_X, p_Y, p_Z, GetMap()->GetVisibilityRange()))
            {
                UnsummonPetTemporaryIfAny();
                UnsummonCurrentBattlePetIfAny(true);
            }
        }

        if (!(p_Options & TeleportToOptions::TELE_TO_NOT_LEAVE_COMBAT))
            CombatStop();

        /// This will be used instead of the current location in SaveToDB
        m_teleport_dest = WorldLocation(p_MapID, p_X, p_Y, p_Z, p_O);
        SetFallInformation(0, p_Z);

        /// Code for finish transfer called in WorldSession::HandleMovementOpcodes()
        /// At client packet CMSG_MOVE_TELEPORT_ACK
        SetSemaphoreTeleportNear(true);
        /// Near teleport, triggering send CMSG_MOVE_TELEPORT_ACK from client at landing
        if (!GetSession()->PlayerLogout())
            SendTeleportPacket(m_teleport_dest);
    }
    else
    {
        /// Pandaria
        if (p_MapID == 870  && getLevel() < 85 && getClass() != Classes::CLASS_MONK  && !isGameMaster())
            return false;

        /// Deepholm
        if (p_MapID == 646  && getLevel() < 80 && !isGameMaster())
            return false;

        if (GetMapId() == 860 && GetTeamId() == TeamId::TEAM_NEUTRAL)
            return false;

        /// Far teleport to another map
        Map* l_OldMap = IsInWorld() ? GetMap() : nullptr;
        /// Check if we can enter before stopping combat / removing pet / totems / interrupting spells

        /// Check enter rights before map getting to avoid creating instance copy for player
        /// This check not dependent from map instance copy and same for all instance copies of selected map
        if (!sMapMgr->CanPlayerEnter(p_MapID, this, false))
            return false;

        if (Group* l_Group = GetGroup())
        {
            if (l_MapEntry->IsDungeon())
                l_Group->IncrementPlayersInInstance();
            else
                l_Group->DecrementPlayersInInstance();
        }

        /// I think this always returns true. Correct me if I am wrong.
        /// If the map is not created, assume it is possible to enter it.
        /// It will be created in the WorldPortAck.
        /// Lets reset near teleport flag if it wasn't reset during chained teleports
        SetSemaphoreTeleportNear(false);

        /// Setup delayed teleport flag
        SetDelayedTeleportFlag(IsCanDelayTeleport());

        /// If teleport spell is casted in Unit::Update() func
        /// Then we need to delay it until update process will be finished
        if (IsHasDelayedTeleport())
        {
            SetSemaphoreTeleportFar(true);

            /// Lets save teleport destination for player
            m_teleport_dest = WorldLocation(p_MapID, p_X, p_Y, p_Z, p_O);
            m_teleport_options = p_Options;
            return true;
        }

        SetSelection(0);
        CombatStop();
        ResetContestedPvP();

        /// Remove player from battleground on far teleport (when changing maps)
        if (Battleground const* l_Battleground = GetBattleground())
        {
            /// Note: at battleground join battleground id set before teleport
            /// And we already will found "current" battleground
            /// Just need check that this is targeted map or leave

            /// Don't teleport to entry point
            if (l_Battleground->GetMapId() != p_MapID)
                LeaveBattleground(false);
        }

        /// Remove arena spell coldowns/buffs now to also remove pet's cooldowns before it's temporarily unsummoned
        if (l_MapEntry->IsBattleArena())
        {
            RemoveArenaSpellCooldowns(true);
            RemoveArenaAuras();

            if (l_Pet)
                l_Pet->RemoveArenaAuras();
        }

        /// Remove pet on map change
        if (l_Pet)
            UnsummonPetTemporaryIfAny();

        UnsummonCurrentBattlePetIfAny(true);

        /// Remove stealth on map change
        if (HasAuraType(AuraType::SPELL_AURA_MOD_STEALTH))
        {
            RemoveAurasByType(AuraType::SPELL_AURA_MOD_STEALTH);

            switch (getClass())
            {
                case Classes::CLASS_ROGUE:
                    RemoveSpellCooldown(1784);
                    RemoveSpellCooldown(115191);
                    break;
                case Classes::CLASS_DRUID:
                    RemoveSpellCooldown(5215);
                    break;
                default:
                    break;
            }
        }

        /// Remove all dyn objects and AreaTrigger
        RemoveAllDynObjects();
        RemoveAllAreasTrigger();

        /// Stop spellcasting
        /// Not attempt interrupt teleportation spell at caster teleport
        if (!(p_Options & TeleportToOptions::TELE_TO_SPELL))
        {
            if (IsNonMeleeSpellCasted(true))
                InterruptNonMeleeSpells(true);
        }

        /// Remove auras before removing from map...
        RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags::AURA_INTERRUPT_FLAG_CHANGE_MAP | SpellAuraInterruptFlags::AURA_INTERRUPT_FLAG_MOVE | SpellAuraInterruptFlags::AURA_INTERRUPT_FLAG_TURNING);

        if (!GetSession()->PlayerLogout())
        {
            /// Send transfer packets
            bool l_TransferSpellID = false;

            WorldPacket l_Data(Opcodes::SMSG_TRANSFER_PENDING, 50);

            l_Data << uint32(p_MapID);
            l_Data.WriteBit(m_transport != nullptr);
            l_Data.WriteBit(0);
            l_Data.FlushBits();

            if (m_transport)
                l_Data << m_transport->GetEntry() << GetMapId();

            if (l_TransferSpellID)
                l_Data << uint32(0);

            GetSession()->SendPacket(&l_Data);
        }

        /// Remove from old map now
        if (l_OldMap)
            l_OldMap->RemovePlayerFromMap(this, false);

        /// New final coordinates
        float l_FinalX = p_X;
        float l_FinalY = p_Y;
        float l_FinalZ = p_Z;
        float l_FinalO = p_O;

        if (m_transport)
        {
            l_FinalX += m_movementInfo.t_pos.GetPositionX();
            l_FinalY += m_movementInfo.t_pos.GetPositionY();
            l_FinalZ += m_movementInfo.t_pos.GetPositionZ();
            l_FinalO += m_movementInfo.t_pos.GetOrientation();
        }

        m_teleport_dest = WorldLocation(p_MapID, l_FinalX, l_FinalY, l_FinalZ, l_FinalO);
        SetFallInformation(0, l_FinalZ);

        /// If the player is saved before worldportack (at logout for example)
        /// This will be used instead of the current location in SaveToDB
        if (!GetSession()->PlayerLogout())
        {
            WorldPacket l_Data(Opcodes::SMSG_NEW_WORLD, 4 + 4 + 4 + 4 + 4 + 4);
            l_Data << uint32(p_MapID);                                  ///< uint32
            l_Data << float(m_teleport_dest.GetPositionX());            ///< float
            l_Data << float(m_teleport_dest.GetPositionY());            ///< float
            l_Data << float(m_teleport_dest.GetPositionZ());            ///< float
            l_Data << float(m_teleport_dest.GetOrientation());          ///< float
            l_Data << uint32(0);                                        ///< uint32 => TransferSpellID
            GetSession()->SendPacket(&l_Data);

            SendSavedInstances();
        }

        /// Move packet sent by client always after far teleport
        /// Code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
        SetSemaphoreTeleportFar(true);
    }

    return true;
}

/// MUST be call with "sMapMgr::AddCriticalOperation"
void Player::SwitchToPhasedMap(uint32 p_MapID)
{
    MapEntry const* l_MapEntry = sMapStore.LookupEntry(p_MapID);
    if (!l_MapEntry)
        return;

    // Check enter rights before map getting to avoid creating instance copy for player
    // this check not dependent from map instance copy and same for all instance copies of selected map
    if (!sMapMgr->CanPlayerEnter(p_MapID, this, false))
        return;

    if (Group* l_Group = GetGroup())
    {
        if (l_MapEntry->IsDungeon())
            l_Group->IncrementPlayersInInstance();
        else
            l_Group->DecrementPlayersInInstance();
    }

    SetSelection(0);
    CombatStop();
    ResetContestedPvP();

    // Remove player from battleground on far teleport (when changing maps)
    if (Battleground const* l_Battleground = GetBattleground())
    {
        if (l_Battleground->GetMapId() != p_MapID)
            LeaveBattleground(false);
    }

    // Remove pet on map change
    if (Pet* l_Pet = GetPet()) ///< l_Pet is unused
        UnsummonPetTemporaryIfAny();

    UnsummonCurrentBattlePetIfAny(true);

    // Remove all dynamic objects and AreaTrigger
    RemoveAllDynObjects();
    RemoveAllAreasTrigger();

    // Stop spellcasting
    // Not attempt interrupt teleportation spell at caster teleport
    if (IsNonMeleeSpellCasted(true))
        InterruptNonMeleeSpells(true);

    // Remove auras before removing from map...
    RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);

    // Remove from old map now
    if (Map* l_OldMap = IsInWorld() ? GetMap() : NULL)
        l_OldMap->RemovePlayerFromMap(this, false);

    // Relocate the player to the teleport destination
    Map* l_NewMap = sMapMgr->CreateMap(p_MapID, this);
    if (!l_NewMap || !l_NewMap->CanEnter(this))
        return;

    // New final coordinates
    float l_X = GetPositionX();
    float l_Y = GetPositionY();
    float l_Z = GetPositionZ();
    float l_Orientation = GetOrientation();
    m_teleport_dest = WorldLocation(p_MapID, l_X, l_Y, l_Z, l_Orientation);
    SetFallInformation(0, l_Z);
    WorldLocation const l_NewLoc = GetTeleportDest();

    Relocate(&l_NewLoc);
    ResetMap();
    SetMap(l_NewMap);

    if (!GetSession()->PlayerLogout())
    {
        WorldPacket l_Data(SMSG_NEW_WORLD, 4 + 4 + 4 + 4 + 4 + 4);

        l_Data << uint32(p_MapID);                                  ///< uint32
        l_Data << float(m_teleport_dest.GetPositionX());            ///< float
        l_Data << float(m_teleport_dest.GetPositionY());            ///< float
        l_Data << float(m_teleport_dest.GetPositionZ());            ///< float
        l_Data << float(m_teleport_dest.GetOrientation());          ///< float
        l_Data << uint32(21);                                       ///< Reason

        GetSession()->SendPacket(&l_Data);
    }

    GetMap()->AddPlayerToMap(this, true);

    // Update zone immediately, otherwise leave channel will cause crash in mtmap
    uint32 l_NewZone, l_NewArea;
    GetZoneAndAreaId(l_NewZone, l_NewArea, true);
    UpdateZone(l_NewZone, l_NewArea);
}

bool Player::TeleportToBGEntryPoint()
{
    if (m_bgData.joinPos.m_mapId == MAPID_INVALID)
        return false;

    ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
    ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
    ScheduleDelayedOperation(DELAYED_BG_GROUP_RESTORE);
    return TeleportTo(m_bgData.joinPos);
}

void Player::ProcessDelayedOperations()
{
    if (m_DelayedOperations == 0)
        return;

    if (m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
    {
        ResurrectPlayer(0.0f, false);

        if (GetMaxHealth() > _resurrectionData->Health)
            SetHealth(_resurrectionData->Health);
        else
            SetFullHealth();

        if (uint32(GetMaxPower(POWER_MANA)) > _resurrectionData->Mana)
            SetPower(POWER_MANA, _resurrectionData->Mana);
        else
            SetPower(POWER_MANA, GetMaxPower(POWER_MANA));

        SetPower(POWER_RAGE, 0);
        SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
        SetPower(POWER_ECLIPSE, 0);

        if (uint32 aura = _resurrectionData->Aura)
            CastSpell(this, aura, true, NULL, nullptr, _resurrectionData->GUID);

        SpawnCorpseBones();

        /// Resurrecting - 60s aura preventing client from new res spells
        RemoveAura(160029);
    }

    if (m_DelayedOperations & DELAYED_SAVE_PLAYER)
        SaveToDB();

    if (m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
        CastSpell(this, 26013, true);               // Deserter

    if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
    {
        if (m_bgData.mountSpell)
        {
            CastSpell(this, m_bgData.mountSpell, true);
            m_bgData.mountSpell = 0;
        }
    }

    if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
    {
        if (m_bgData.HasTaxiPath())
        {
            m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
            m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
            m_bgData.ClearTaxiPath();

            ContinueTaxiFlight();
        }
    }

    if (m_DelayedOperations & DELAYED_BG_GROUP_RESTORE)
    {
        if (Group *g = GetGroup())
            g->SendUpdateToPlayer(GetGUID());
    }

    if (m_DelayedOperations & DELAYED_PET_BATTLE_INITIAL)
    {
        if (PetBattle* l_Battle = sPetBattleSystem->GetBattle(_petBattleId))
        {
            uint8 l_TeamID = l_Battle->Teams[PETBATTLE_TEAM_1]->OwnerGuid == GetGUID() ? PETBATTLE_TEAM_1 : PETBATTLE_TEAM_2;

            PetBattleRequest l_Request;
            memcpy(&l_Request, &l_Battle->PvPMatchMakingRequest, sizeof(PetBattleRequest));

            if (l_TeamID == PETBATTLE_TEAM_2)
            {
                std::swap(l_Request.TeamPosition[PETBATTLE_TEAM_1][0], l_Request.TeamPosition[PETBATTLE_TEAM_2][0]);
                std::swap(l_Request.TeamPosition[PETBATTLE_TEAM_1][1], l_Request.TeamPosition[PETBATTLE_TEAM_2][1]);
                std::swap(l_Request.TeamPosition[PETBATTLE_TEAM_1][2], l_Request.TeamPosition[PETBATTLE_TEAM_2][2]);
            }

            l_Battle->PvPMatchMakingRequest.PetBattleCenterPosition[2] = GetMap()->GetHeight(l_Battle->PvPMatchMakingRequest.PetBattleCenterPosition[0], l_Battle->PvPMatchMakingRequest.PetBattleCenterPosition[1], MAX_HEIGHT);

            GetSession()->SendPetBattleFinalizeLocation(&l_Request);

            SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED | UNIT_FLAG_IMMUNE_TO_NPC);
            SetFacingTo(GetAngle(l_Battle->PvPMatchMakingRequest.TeamPosition[!l_TeamID][0], l_Battle->PvPMatchMakingRequest.TeamPosition[!l_TeamID][1]));
            SetRooted(true);

            if (!l_Battle->PvPMatchMakingRequest.IsPvPReady[l_TeamID])
                l_Battle->PvPMatchMakingRequest.IsPvPReady[l_TeamID] = true;

            if (l_Battle->PvPMatchMakingRequest.IsPvPReady[PETBATTLE_TEAM_1] == true && l_Battle->PvPMatchMakingRequest.IsPvPReady[PETBATTLE_TEAM_2] == true)
                l_Battle->Begin();
        }
    }

    //we have executed ALL delayed ops, so clear the flag
    m_DelayedOperations = 0;
}

void Player::AddToWorld()
{
    ///- Do not add/remove the player from the object storage
    ///- It will crash when updating the ObjectAccessor
    ///- The player should only be added when logging in
    Unit::AddToWorld();

    for (uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
        if (m_items[i])
            m_items[i]->AddToWorld();
}

void Player::RemoveFromWorld()
{
    // cleanup
    if (IsInWorld())
    {
        ///- Release charmed creatures, unsummon totems and remove pets/guardians
        StopCastingCharm();
        StopCastingBindSight();
        UnsummonPetTemporaryIfAny();
        UnsummonCurrentBattlePetIfAny(true);
        sOutdoorPvPMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
        sBattlefieldMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
    }

    ///- Do not add/remove the player from the object storage
    ///- It will crash when updating the ObjectAccessor
    ///- The player should only be removed when logging out
    Unit::RemoveFromWorld();

    for (uint8 i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
    {
        if (m_items[i])
            m_items[i]->RemoveFromWorld();
    }

    for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
        iter->second->RemoveFromWorld();

    if (m_uint32Values)
    {
        if (WorldObject* viewpoint = GetViewpoint())
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player %s has viewpoint %u %u when removed from world", GetName(), viewpoint->GetEntry(), viewpoint->GetTypeId());
            SetViewpoint(viewpoint, false);
        }
    }
}

void Player::RegenerateAll()
{
    m_regenTimerCount += m_RegenPowerTimer;

    Classes l_Class = (Classes)getClass();
    switch (l_Class)
    {
        case Classes::CLASS_PALADIN:
            m_holyPowerRegenTimerCount += m_RegenPowerTimer;
            break;
        case Classes::CLASS_MONK:
            m_chiPowerRegenTimerCount += m_RegenPowerTimer;
            break;
        case Classes::CLASS_HUNTER:
            m_focusRegenTimerCount += m_RegenPowerTimer;
            break;
        case Classes::CLASS_WARLOCK:
        {
            switch (GetSpecializationId())
            {
                case SpecIndex::SPEC_WARLOCK_DEMONOLOGY:
                    m_demonicFuryPowerRegenTimerCount += m_RegenPowerTimer;
                    break;
                case SpecIndex::SPEC_WARLOCK_AFFLICTION:
                    m_soulShardsRegenTimerCount += m_RegenPowerTimer;
                    break;
                default:
                    break;
            }
            break;
        }
        case Classes::CLASS_DEATH_KNIGHT:   ///< Runes act as cooldowns, and they don't need to send any data
        {
            m_runicPowerRegenTimerCount += m_RegenPowerTimer;

            for (uint8 l_I = 0; l_I < MAX_RUNES; l_I += 2)
            {
                uint8 l_RuneToRegen = l_I;
                uint32 l_Cooldown = GetRuneCooldown(l_I);
                uint32 l_SecondRuneCooldown = GetRuneCooldown(l_I + 1);
                // Regenerate second rune of the same type only after first rune is off the cooldown
                if (l_SecondRuneCooldown && (l_Cooldown > l_SecondRuneCooldown || !l_Cooldown))
                {
                    l_RuneToRegen = l_I + 1;
                    l_Cooldown = l_SecondRuneCooldown;
                }

                if (l_Cooldown)
                    SetRuneCooldown(l_RuneToRegen, (l_Cooldown > m_RegenPowerTimer) ? l_Cooldown - m_RegenPowerTimer : 0);
            }
            break;
        }
        default:
            break;
    }

    Regenerate(POWER_MANA);
    Regenerate(POWER_ENERGY);

    if (m_regenTimerCount >= 2000)
    {
        // Not in combat or they have regeneration
        if (!isInCombat() || IsPolymorphed() || m_baseHealthRegen ||
            HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
            HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT))
        {
            RegenerateHealth();
        }

        Regenerate(POWER_RAGE);

        m_regenTimerCount -= 2000;
    }

    if (m_focusRegenTimerCount >= 1000)
    {
        if (l_Class == CLASS_HUNTER)
            Regenerate(POWER_FOCUS);

        m_focusRegenTimerCount -= 1000;
    }

    if (m_holyPowerRegenTimerCount >= 10000 && l_Class == CLASS_PALADIN)
    {
        Regenerate(POWER_HOLY_POWER);
        m_holyPowerRegenTimerCount -= 10000;
    }

    if (m_runicPowerRegenTimerCount >= 1000 && l_Class == CLASS_DEATH_KNIGHT)
    {
        Regenerate(POWER_RUNIC_POWER);
        m_runicPowerRegenTimerCount -= 1000;
    }

    if (m_chiPowerRegenTimerCount >= 15000 && l_Class == CLASS_MONK)
    {
        Regenerate(POWER_CHI);
        m_chiPowerRegenTimerCount -= 15000;
    }

    if (m_demonicFuryPowerRegenTimerCount >= 100 && l_Class == CLASS_WARLOCK && (GetSpecializationId() == SPEC_WARLOCK_DEMONOLOGY))
    {
        Regenerate(POWER_DEMONIC_FURY);
        m_demonicFuryPowerRegenTimerCount -= 100;
    }

    if (m_soulShardsRegenTimerCount >= 20000 && l_Class == CLASS_WARLOCK && (GetSpecializationId() == SPEC_WARLOCK_AFFLICTION))
    {
        Regenerate(POWER_SOUL_SHARDS);
        m_soulShardsRegenTimerCount -= 20000;
    }

    m_RegenPowerTimer = 0;
}

void Player::Regenerate(Powers power)
{
    int32 maxValue = GetMaxPower(power);
    if (!maxValue)
        return;

    int32 curValue = GetPower(power);

    /// @Todo: possible use of miscvalueb instead of amount
    if (HasAuraTypeWithValue(SPELL_AURA_PREVENT_REGENERATE_POWER, power))
        return;

    /// Skip regeneration for power type we cannot have // Custom MoP script
    uint32 powerIndex = GetPowerIndex(power, getClass());
    if (powerIndex == MAX_POWERS)
        return;

    float addvalue = 0.0f;

    /// Powers now benefit from haste.
    float HastePct = 2.0f - GetFloatValue(UNIT_FIELD_MOD_HASTE_REGEN);

    bool l_PreventDefault = false;
    sScriptMgr->OnPlayerRegenPower(this, power, addvalue, l_PreventDefault);

    if (!l_PreventDefault)
    {
        switch (power)
        {
            /// Regenerate Mana
            case POWER_MANA:
            {
                float ManaIncreaseRate = sWorld->getRate(RATE_POWER_MANA);

                if (isInCombat())
                    addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) *  ManaIncreaseRate * ((0.001f * m_RegenPowerTimer) + CalculatePct(0.001f, HastePct));
                else
                    addvalue += GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) *  ManaIncreaseRate * ((0.001f * m_RegenPowerTimer) + CalculatePct(0.001f, HastePct));
                break;
            }
            /// Regenerate Rage
            case POWER_RAGE:
            {
                if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
                {
                    float RageDecreaseRate = sWorld->getRate(RATE_POWER_RAGE_LOSS);
                    addvalue += (-25 * RageDecreaseRate / HastePct); ///< 2.5 rage by tick (= 2 seconds => 1.25 rage/sec)
                }
                break;
            }
            /// Regenerate Focus
            case POWER_FOCUS:
            {
                float l_HastePct = 1.0f / GetFloatValue(UNIT_FIELD_MOD_HASTE);
                addvalue += 4.0f * l_HastePct * sWorld->getRate(RATE_POWER_FOCUS);
                break;
            }
            /// Regenerate Energy
            case POWER_ENERGY:
                addvalue += ((0.01f * m_RegenPowerTimer) * sWorld->getRate(RATE_POWER_ENERGY) * HastePct);
                break;
            /// Regenerate Runic Power
            case POWER_RUNIC_POWER:
            {
                float RunicPowerDecreaseRate = sWorld->getRate(RATE_POWER_RUNICPOWER_LOSS);
                if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
                {
                    addvalue += (-15 * RunicPowerDecreaseRate / HastePct); ///< 1.5 RunicPower by tick
                }
                if (isInCombat() && HasAura(50029))
                    addvalue += 10.0f * RunicPowerDecreaseRate; ///< 1 RunicPower by tick

                break;
            }
            /// Regenerate Holy Power
            case POWER_HOLY_POWER:
            {
                if (!isInCombat())
                    addvalue += -1.0f; ///< remove 1 each 10 sec
                break;
            }
            /// Regenerate Chi
            case POWER_CHI:
            {
                if (!isInCombat())
                    addvalue += -1.0f; ///< remove 1 each 10 sec
                break;
            }
            /// Regenerate Demonic Fury
            case POWER_DEMONIC_FURY:
            {
                if (!isInCombat() && GetPower(POWER_DEMONIC_FURY) >= 300 && GetShapeshiftForm() != FORM_METAMORPHOSIS)
                    addvalue += -1.0f;    ///< remove 1 each 100ms
                else if (!isInCombat() && GetPower(POWER_DEMONIC_FURY) < 200 && GetShapeshiftForm() != FORM_METAMORPHOSIS)
                    addvalue += 1.0f;     ///< give 1 each 100ms while player has less than 200 demonic fury

                if (!HasAura(114168))
                {
                    if (GetPower(POWER_DEMONIC_FURY) <= 40)
                    {
                        if (HasAura(103958))
                            RemoveAura(103958);

                        if (HasAura(54879))
                            RemoveAura(54879);
                    }
                }

                /// Demonic Fury visuals
                if (GetPower(POWER_DEMONIC_FURY) == 1000)
                    CastSpell(this, 131755, true);
                else if (GetPower(POWER_DEMONIC_FURY) >= 500)
                {
                    CastSpell(this, 122738, true);

                    if (HasAura(131755))
                        RemoveAura(131755);
                }
                else
                {
                    if (HasAura(122738))
                        RemoveAura(122738);
                    if (HasAura(131755))
                        RemoveAura(131755);
                }

                break;
            }
            /// Regenerate Soul Shards
            case POWER_SOUL_SHARDS:
            {
                /// If isn't in combat, gain 1 shard every 20s
                if (!isInCombat())
                    SetPower(POWER_SOUL_SHARDS, GetPower(POWER_SOUL_SHARDS) + 100, true);

                if (HasAura(56241))
                {
                    if (GetPower(POWER_SOUL_SHARDS) < 200 && GetPower(POWER_SOUL_SHARDS) >= 100)
                    {
                        RemoveAura(123730);            ///< 2 shards visual
                        CastSpell(this, 123728, true); ///< 1 shard visual
                    }
                    else if (GetPower(POWER_SOUL_SHARDS) < 300)
                    {
                        CastSpell(this, 123728, true); ///< 1 shard visual
                        CastSpell(this, 123730, true); ///< 2 shards visual
                        RemoveAura(123731);            ///< 3 shards visual
                    }
                    else if (GetPower(POWER_SOUL_SHARDS) < 400)
                    {
                        CastSpell(this, 123728, true); ///< 1 shard visual
                        CastSpell(this, 123730, true); ///< 2 shards visual
                        CastSpell(this, 123731, true); ///< 3 shards visual
                    }
                }
                break;
            }
            default:
                break;
        }
    }

    /// Mana regen calculated in Player::UpdateManaRegen()
    if (power != POWER_MANA && power != POWER_CHI && power != POWER_HOLY_POWER && power != POWER_SOUL_SHARDS && power != POWER_BURNING_EMBERS && power != POWER_DEMONIC_FURY)
    {
        AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
        for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
            if (Powers((*i)->GetMiscValue()) == power)
                AddPct(addvalue, (*i)->GetAmount());

        // Butchery requires combat for this effect
        if (power != POWER_RUNIC_POWER || isInCombat())
            addvalue += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_POWER_REGEN, power) * ((power != POWER_ENERGY) ? m_regenTimerCount : m_RegenPowerTimer) / (5 * IN_MILLISECONDS);
    }

    if (addvalue < 0.0f)
    {
        if (curValue == 0)
            return;
    }
    else if (addvalue > 0.0f)
    {
        if (curValue == maxValue)
            return;
    }
    else
        return;

    addvalue += m_powerFraction[powerIndex];

    int32 integerValue = uint32(fabs(addvalue));

    if (addvalue < 0.0f)
    {
        if (curValue > integerValue)
        {
            curValue -= integerValue;
            m_powerFraction[powerIndex] = addvalue + integerValue;
        }
        else
        {
            curValue = 0;
            m_powerFraction[powerIndex] = 0;
        }
    }
    else
    {
        curValue += integerValue;

        if (curValue > maxValue)
        {
            curValue = maxValue;
            m_powerFraction[powerIndex] = 0;
        }
        else
            m_powerFraction[powerIndex] = addvalue - integerValue;
    }

    SetPower(power, curValue, true);
}

void Player::RegenerateHealth()
{
    uint32 curValue = GetHealth();
    uint32 maxValue = GetMaxHealth();

    if (curValue >= maxValue)
        return;

    float HealthIncreaseRate = sWorld->getRate(RATE_HEALTH);

    float addvalue = 0.0f;
    bool inFight = isInCombat();

    // polymorphed case
    if (IsPolymorphed())
        addvalue = (float)GetMaxHealth()/3;
    // normal regen case (maybe partly in combat case)
    else if (!inFight || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
    {
        addvalue = HealthIncreaseRate; ///< addvalue is never read 01/18/16
        if (getLevel() < 15)
            addvalue = (0.20f*((float)GetMaxHealth())/getLevel()*HealthIncreaseRate);
        else
            addvalue = 0.015f*((float)GetMaxHealth())*HealthIncreaseRate;

        AuraEffectList const& mModHealthRegenPct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
        for (AuraEffectList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
            AddPct(addvalue, (*i)->GetAmount());

        addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_REGEN) * 2 * IN_MILLISECONDS / (5 * IN_MILLISECONDS);

        if (inFight)
            ApplyPct(addvalue, GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT));

        if (!IsStandState())
            addvalue *= 1.5f;
    }

    // always regeneration bonus (including combat)
    addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
    addvalue += m_baseHealthRegen / 2.5f;

    if (addvalue < 0)
        addvalue = 0;

    ModifyHealth(int32(addvalue));
}

void Player::ResetAllPowers()
{
    if (getPowerType() == POWER_COMBO_POINT)
        ClearComboPoints();

    SetHealth(GetMaxHealth());
    SetPower(POWER_BURNING_EMBERS, 10);
    SetPower(POWER_CHI, 0);
    SetPower(POWER_DEMONIC_FURY, 200);
    SetPower(POWER_ECLIPSE, 0);
    SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
    SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
    SetPower(POWER_RAGE, 0);
    SetPower(POWER_RUNIC_POWER, 0);
    SetPower(POWER_SHADOW_ORB, 0);
    SetPower(POWER_SOUL_SHARDS, 400);
}

bool Player::CanInteractWithQuestGiver(Object* questGiver)
{
    switch (questGiver->GetTypeId())
    {
        case TYPEID_UNIT:
            return GetNPCIfCanInteractWith(questGiver->GetGUID(), UNIT_NPC_FLAG_QUESTGIVER) != NULL;
        case TYPEID_GAMEOBJECT:
            return GetGameObjectIfCanInteractWith(questGiver->GetGUID(), GAMEOBJECT_TYPE_QUESTGIVER) != NULL;
        case TYPEID_PLAYER:
            return isAlive() && questGiver->ToPlayer()->isAlive();
        case TYPEID_ITEM:
            return isAlive();
        default:
            break;
    }
    return false;
}

/// Temp enum, need more reverse work on LogicOpperators in CGPlayer_C::MatchesCondition
enum
{
    LOGIC_FLAG_01                       = 0x00000001,
    LOGIC_FLAG_02                       = 0x00000002,
    LOGIC_FLAG_03                       = 0x00000004,
    LOGIC_FLAG_04                       = 0x00000008,
    LOGIC_FLAG_05                       = 0x00000010,
    LOGIC_FLAG_06                       = 0x00000020,
    LOGIC_FLAG_COL_0_XOR_RESULT_TRUE    = 0x00010000,
    LOGIC_FLAG_COL_1_XOR_RESULT_TRUE    = 0x00020000,
    LOGIC_FLAG_COL_2_XOR_RESULT_TRUE    = 0x00040000,
    LOGIC_FLAG_COL_3_XOR_RESULT_TRUE    = 0x00080000,
};

std::pair<bool, std::string> Player::EvalPlayerCondition(uint32 p_ConditionsID, bool p_FailIfConditionNotFound) ///< p_FailIfConditionNotFound is unused
{
    PlayerConditionEntry const* l_Entry = sPlayerConditionStore.LookupEntry(p_ConditionsID);

    if (!l_Entry && !sScriptMgr->HasPlayerConditionScript(p_ConditionsID))
        return std::pair<bool, std::string>(false, "Condition entry not found");

    if (sScriptMgr->HasPlayerConditionScript(p_ConditionsID))
    {
        if (!sScriptMgr->EvalPlayerConditionScript(p_ConditionsID, l_Entry, this))
            return std::pair<bool, std::string>(false, "Condition script failed");

        return std::pair<bool, std::string>(true, "");
    }

    auto EvalMatch = [](bool * p_Matches, uint32 p_Flags) -> bool
    {
        bool l_Result = p_Matches[0] && p_Matches[1] && p_Matches[2] && p_Matches[3];
        bool l_FirstMatchFlagMatch  = (!!(p_Flags & LOGIC_FLAG_COL_0_XOR_RESULT_TRUE)) ^ p_Matches[0];
        bool l_SecondMatchFlagMatch = (!!(p_Flags & LOGIC_FLAG_COL_1_XOR_RESULT_TRUE)) ^ p_Matches[1];
        bool l_ThirdMatchFlagMatch  = (!!(p_Flags & LOGIC_FLAG_COL_2_XOR_RESULT_TRUE)) ^ p_Matches[2];
        bool l_FourthMatchFlagMatch = (!!(p_Flags & LOGIC_FLAG_COL_3_XOR_RESULT_TRUE)) ^ p_Matches[3];

        if (p_Flags & LOGIC_FLAG_01)
        {
            if (l_FirstMatchFlagMatch)
                l_Result = l_SecondMatchFlagMatch;
        }
        else if (p_Flags & LOGIC_FLAG_02)
            l_Result = l_FirstMatchFlagMatch | l_SecondMatchFlagMatch;

        if (p_Flags & LOGIC_FLAG_03)
            l_Result = l_Result & l_ThirdMatchFlagMatch;
        else if (p_Flags & LOGIC_FLAG_04)
            l_Result = l_Result | l_ThirdMatchFlagMatch;

        if (p_Flags & LOGIC_FLAG_05)
        {
            if (!l_Result)
                return false;
        }
        else if (p_Flags & LOGIC_FLAG_06)
            l_Result = l_FourthMatchFlagMatch | l_Result;

        return l_Result;
    };

    /// @TODO : Flags

    #pragma region Level conditions
    if (l_Entry->MinLevel != 0 && getLevel() < l_Entry->MinLevel)
        return std::pair<bool, std::string>(false, "Failed on MinLevel => dbc(" + std::to_string(l_Entry->MinLevel) + ") you(" + std::to_string(getLevel()) + ")");
    if (l_Entry->MaxLevel != 0 && getLevel() > l_Entry->MaxLevel)
        return std::pair<bool, std::string>(false, "Failed on MaxLevel => dbc(" + std::to_string(l_Entry->MaxLevel) + ") you(" + std::to_string(getLevel()) + ")");
    #pragma endregion Level conditions

    #pragma region Class, Race, Gender, NativeGender
    if (l_Entry->RaceMask != 0 && (l_Entry->RaceMask & getRaceMask()) == 0)
        return std::pair<bool, std::string>(false, "Failed on RaceMask => dbc(" + std::to_string(l_Entry->RaceMask) + ") you(" + std::to_string(getRaceMask()) + ")");
    if (l_Entry->ClassMask != 0 && (l_Entry->ClassMask & getClassMask()) == 0)
        return std::pair<bool, std::string>(false, "Failed on ClassMask => dbc(" + std::to_string(l_Entry->ClassMask) + ") you(" + std::to_string(getClassMask()) + ")");
    if (l_Entry->Gender != -1 && l_Entry->Gender != getGender())
        return std::pair<bool, std::string>(false, "Failed on Gender => dbc(" + std::to_string(l_Entry->Gender) + ") you(" + std::to_string(getGender()) + ")");
    if (l_Entry->NativeGender != -1 && l_Entry->NativeGender != getGender())
        return std::pair<bool, std::string>(false, "Failed on NativeGender => dbc(" + std::to_string(l_Entry->NativeGender) + ") you(" + std::to_string(getGender()) + ")");
    #pragma endregion Class, Race, Gender, NativeGender

    #pragma region Skills
    for (uint32 l_I = 0; l_I < 4; ++l_I)
    {
        if (l_Entry->SkillID[l_I] != 0)
        {
            if (!HasSkill(l_Entry->SkillID[l_I]))
                return std::pair<bool, std::string>(false, "Failed on SkillID => dbc(" + std::to_string(l_Entry->SkillID[l_I]) + ") you don't known this skill");

            int32 l_Skill = (int32)GetSkillValue(l_Entry->SkillID[l_I]);

            if (l_Entry->MinSkill[l_I] != 0 && l_Skill < l_Entry->MinSkill[l_I])
                return std::pair<bool, std::string>(false, "Failed on MinSkill => dbc(" + std::to_string(l_Entry->MinSkill[l_I]) + ") you(" + std::to_string(l_Skill) + ")");
            if (l_Entry->MaxSkill[l_I] != 0 && l_Skill > l_Entry->MaxSkill[l_I])
                return std::pair<bool, std::string>(false, "Failed on MaxSkill => dbc(" + std::to_string(l_Entry->MaxSkill[l_I]) + ") you(" + std::to_string(l_Skill) + ")");
        }
    }
    #pragma endregion Skills

    /// @TODO : SkillLogic

    #pragma region Language
    if (l_Entry->LanguageID != 0)
    {
        uint32 l_SkillID = lang_description[l_Entry->LanguageID].skill_id;

        if (!HasSkill(l_SkillID))
            return std::pair<bool, std::string>(false, "Failed on LanguageID => dbc(" + std::to_string(l_Entry->LanguageID) + ") you don't known this language");

        int32 l_Skill = (int32)GetSkillValue(l_SkillID);

        if (l_Entry->MinLanguage != 0 && l_Skill < l_Entry->MinLanguage)
            return std::pair<bool, std::string>(false, "Failed on MinLanguage => dbc(" + std::to_string(l_Entry->MinLanguage) + ") you(" + std::to_string(l_Skill) + ")");
        if (l_Entry->MaxLanguage != 0 && l_Skill > l_Entry->MaxLanguage)
            return std::pair<bool, std::string>(false, "Failed on MaxLanguage => dbc(" + std::to_string(l_Entry->MaxLanguage) + ") you(" + std::to_string(l_Skill) + ")");
    }
    #pragma endregion Language

    /// @TODO : MinFaction
    /// @TODO : MinReputation
    /// @TODO : MaxReputation
    /// @TODO : ReputationLogic
    /// @TODO : MinPVPRank
    /// @TODO : MaxPVPRank
    /// @TODO : PVPMedal

    #pragma region PrevQuestLogic, PrevQuestID
    if (l_Entry->PrevQuestID[0] || l_Entry->PrevQuestID[1] || l_Entry->PrevQuestID[2] || l_Entry->PrevQuestID[3])
    {
        bool l_Matches[4] { true, true, true, true };

        if (l_Entry->PrevQuestID[0] != 0) l_Matches[0] = GetQuestRewardStatus(l_Entry->PrevQuestID[0]);
        if (l_Entry->PrevQuestID[1] != 0) l_Matches[1] = GetQuestRewardStatus(l_Entry->PrevQuestID[1]);
        if (l_Entry->PrevQuestID[2] != 0) l_Matches[2] = GetQuestRewardStatus(l_Entry->PrevQuestID[2]);
        if (l_Entry->PrevQuestID[3] != 0) l_Matches[3] = GetQuestRewardStatus(l_Entry->PrevQuestID[3]);

        if (!EvalMatch(l_Matches, l_Entry->PrevQuestLogic))
            return std::pair<bool, std::string>(false, "Failed on PrevQuestID");
    }
    #pragma endregion PrevQuestLogic, PrevQuestID

    #pragma region CurrQuestLogic, CurrQuestID
    if (l_Entry->CurrQuestID[0] || l_Entry->CurrQuestID[1] || l_Entry->CurrQuestID[2] || l_Entry->CurrQuestID[3])
    {
        bool l_Matches[4] { true, true, true, true };

        if (l_Entry->CurrQuestID[0] != 0) l_Matches[0] = HasQuest(l_Entry->CurrQuestID[0]);
        if (l_Entry->CurrQuestID[1] != 0) l_Matches[1] = HasQuest(l_Entry->CurrQuestID[1]);
        if (l_Entry->CurrQuestID[2] != 0) l_Matches[2] = HasQuest(l_Entry->CurrQuestID[2]);
        if (l_Entry->CurrQuestID[3] != 0) l_Matches[3] = HasQuest(l_Entry->CurrQuestID[3]);

        if (!EvalMatch(l_Matches, l_Entry->CurrQuestLogic))
            return std::pair<bool, std::string>(false, "Failed on CurrQuestID");
    }
    #pragma endregion CurrQuestLogic, CurrQuestID

    #pragma region CurrentCompletedQuestLogic, CurrentCompletedQuestID
    if (l_Entry->CurrentCompletedQuestID[0] || l_Entry->CurrentCompletedQuestID[1] || l_Entry->CurrentCompletedQuestID[2] || l_Entry->CurrentCompletedQuestID[3])
    {
        bool l_Matches[4] { true, true, true, true };

        if (l_Entry->CurrentCompletedQuestID[0] != 0) l_Matches[0] = GetQuestRewardStatus(l_Entry->CurrentCompletedQuestID[0]);
        if (l_Entry->CurrentCompletedQuestID[1] != 0) l_Matches[1] = GetQuestRewardStatus(l_Entry->CurrentCompletedQuestID[1]);
        if (l_Entry->CurrentCompletedQuestID[2] != 0) l_Matches[2] = GetQuestRewardStatus(l_Entry->CurrentCompletedQuestID[2]);
        if (l_Entry->CurrentCompletedQuestID[3] != 0) l_Matches[3] = GetQuestRewardStatus(l_Entry->CurrentCompletedQuestID[3]);

        if (!EvalMatch(l_Matches, l_Entry->CurrentCompletedQuestLogic))
            return std::pair<bool, std::string>(false, "Failed on CurrentCompletedQuestID");
    }
    #pragma endregion CurrentCompletedQuestLogic, CurrentCompletedQuestID

    #pragma region SpellLogic, SpellID
    if (l_Entry->SpellID[0] || l_Entry->SpellID[1] || l_Entry->SpellID[2] || l_Entry->SpellID[3])
    {
        bool l_Matches[4] { true, true, true, true };

        if (l_Entry->SpellID[0] != 0) l_Matches[0] = HasSpell(l_Entry->SpellID[0]);
        if (l_Entry->SpellID[1] != 0) l_Matches[1] = HasSpell(l_Entry->SpellID[1]);
        if (l_Entry->SpellID[2] != 0) l_Matches[2] = HasSpell(l_Entry->SpellID[2]);
        if (l_Entry->SpellID[3] != 0) l_Matches[3] = HasSpell(l_Entry->SpellID[3]);

        if (!EvalMatch(l_Matches, l_Entry->SpellLogic))
            return std::pair<bool, std::string>(false, "Failed on SpellID");
    }
    #pragma endregion SpellLogic, SpellID

    #pragma region ItemLogic, ItemID, ItemCount
    if (l_Entry->ItemID[0] || l_Entry->ItemID[1] || l_Entry->ItemID[2] || l_Entry->ItemID[3])
    {
        bool l_Matches[4] { true, true, true, true };

        if (l_Entry->ItemID[0] != 0) l_Matches[0] = HasItemCount(l_Entry->ItemID[0], !l_Entry->ItemCount[0] ? 1 : l_Entry->ItemCount[0], false);
        if (l_Entry->ItemID[1] != 0) l_Matches[1] = HasItemCount(l_Entry->ItemID[0], !l_Entry->ItemCount[1] ? 1 : l_Entry->ItemCount[1], false);
        if (l_Entry->ItemID[2] != 0) l_Matches[2] = HasItemCount(l_Entry->ItemID[0], !l_Entry->ItemCount[2] ? 1 : l_Entry->ItemCount[2], false);
        if (l_Entry->ItemID[3] != 0) l_Matches[3] = HasItemCount(l_Entry->ItemID[0], !l_Entry->ItemCount[3] ? 1 : l_Entry->ItemCount[3], false);

        if (!EvalMatch(l_Matches, l_Entry->ItemLogic))
            return std::pair<bool, std::string>(false, "Failed on ItemID");
    }
    #pragma endregion ItemLogic, ItemID, ItemCount

    /// @TODO : ItemFlags

    #pragma region Explored
    auto IsAreaExplored = [this](uint32 p_AreaID) -> bool ///< p_AreaID is unused
    {
        uint16 l_AreaFlag = sAreaStore.LookupEntry(0) ? sAreaStore.LookupEntry(0)->AreaBit : 0xFFFF;

        if (l_AreaFlag == 0xFFFF)
            return false;
        int l_Offset = l_AreaFlag / 32;

        if (l_Offset >= PLAYER_EXPLORED_ZONES_SIZE)
            return false;

        uint32 l_Value = (uint32)(1 << (l_AreaFlag % 32));

        if (!(GetUInt32Value(PLAYER_FIELD_EXPLORED_ZONES + l_Offset) & l_Value))
            return false;

        return true;
    };

    if (l_Entry->Explored[0] != 0 && !IsAreaExplored(l_Entry->Explored[0]))
        return std::pair<bool, std::string>(false, "Failed on Explored[0] => dbc(" + std::to_string(l_Entry->Explored[0]) + ") area is not explored");
    if (l_Entry->Explored[1] != 0 && !IsAreaExplored(l_Entry->Explored[1]))
        return std::pair<bool, std::string>(false, "Failed on Explored[1] => dbc(" + std::to_string(l_Entry->Explored[1]) + ") area is not explored");
    #pragma endregion Explored

    /// @TODO : Time

    #pragma region AuraSpellLogic, AuraSpellID
    if (l_Entry->AuraSpellID[0] || l_Entry->AuraSpellID[1] || l_Entry->AuraSpellID[2] || l_Entry->AuraSpellID[3]|| l_Entry->AuraSpellID[4])
    {
        bool l_Matches[] { true, true, true, true, true };

        if (l_Entry->AuraSpellID[0] != 0) l_Matches[0] = HasAura(l_Entry->AuraSpellID[0]);
        if (l_Entry->AuraSpellID[1] != 0) l_Matches[1] = HasAura(l_Entry->AuraSpellID[1]);
        if (l_Entry->AuraSpellID[2] != 0) l_Matches[2] = HasAura(l_Entry->AuraSpellID[2]);
        if (l_Entry->AuraSpellID[3] != 0) l_Matches[3] = HasAura(l_Entry->AuraSpellID[3]);
        if (l_Entry->AuraSpellID[4] != 0) l_Matches[4] = HasAura(l_Entry->AuraSpellID[4]);

        if (!EvalMatch(l_Matches, l_Entry->AuraSpellLogic))
            return std::pair<bool, std::string>(false, "Failed on AuraSpellID");
    }
    #pragma endregion AuraSpellLogic, AuraSpellID

    #pragma region WorldStateExpressionID
    if (l_Entry->WorldStateExpressionID != 0)
    {
        WorldStateExpressionEntry const* l_Expression = sWorldStateExpressionStore.LookupEntry(l_Entry->WorldStateExpressionID);

        if (!l_Expression)
            return std::pair<bool, std::string>(false, "Failed on WorldStateExpressionID => DBC WorldStateExpression entry not found");

        if (!l_Expression->Eval(this))
            return std::pair<bool, std::string>(false, "Failed on WorldStateExpressionID => eval failed");
    }
    #pragma endregion WorldStateExpressionID

    #pragma region Weather
    if (l_Entry->WeatherID != 0)
    {
        AreaTableEntry const* l_Zone = GetAreaEntryByAreaID(GetZoneId());

        if (!l_Zone)
            return std::pair<bool, std::string>(false, "Failed on WeatherID => DBC AreaTable entry not found");

        Weather * l_Weather = WeatherMgr::FindWeather(l_Zone->ID);

        if (!l_Weather)
            return std::pair<bool, std::string>(false, "Failed on WeatherID => no valid weather found");

        if (l_Weather->GetType() != l_Entry->WeatherID) ///< Comparison of integers of different signs: 'const unsigned int' and 'int32' (aka 'int')
            return std::pair<bool, std::string>(false, "Failed on WeatherID => dbc(" + std::to_string(l_Entry->WeatherID) + ") you(" + std::to_string(l_Weather->GetType()) + ")");
    }
    #pragma endregion Weather

    /// @TODO : PartyStatus
    /// @TODO : LifetimeMaxPVPRank

    #pragma region AchievementLogic, Achievement
    if (l_Entry->Achievement[0] || l_Entry->Achievement[1] || l_Entry->Achievement[2] || l_Entry->Achievement[3])
    {
        bool l_Matches[4] { true, true, true, true };

        if (l_Entry->Achievement[0] != 0) l_Matches[0] = GetAchievementMgr().HasAchieved(l_Entry->Achievement[0]);
        if (l_Entry->Achievement[1] != 0) l_Matches[1] = GetAchievementMgr().HasAchieved(l_Entry->Achievement[1]);
        if (l_Entry->Achievement[2] != 0) l_Matches[2] = GetAchievementMgr().HasAchieved(l_Entry->Achievement[2]);
        if (l_Entry->Achievement[3] != 0) l_Matches[3] = GetAchievementMgr().HasAchieved(l_Entry->Achievement[3]);

        if (!EvalMatch(l_Matches, l_Entry->AchievementLogic))
            return std::pair<bool, std::string>(false, "Failed on Achievement");
    }
    #pragma endregion AchievementLogic, Achievement

    /// @TODO : LfgLogic
    /// @TODO : LfgStatus
    /// @TODO : LfgCompare
    /// @TODO : LfgValue

    #pragma region AreaLogic, AreaID
    if (l_Entry->AreaID[0] || l_Entry->AreaID[1] || l_Entry->AreaID[2] || l_Entry->AreaID[3])
    {
        bool l_Matches[4] { true, true, true, true };

        if (l_Entry->AreaID[0] != 0) l_Matches[0] = l_Entry->AreaID[0] == GetAreaId(); ///< Comparison of integers of different signs: 'const unsigned int' and 'int32' (aka 'int')
        if (l_Entry->AreaID[1] != 0) l_Matches[1] = l_Entry->AreaID[1] == GetAreaId(); ///< Comparison of integers of different signs: 'const unsigned int' and 'int32' (aka 'int')
        if (l_Entry->AreaID[2] != 0) l_Matches[2] = l_Entry->AreaID[2] == GetAreaId(); ///< Comparison of integers of different signs: 'const unsigned int' and 'int32' (aka 'int')
        if (l_Entry->AreaID[3] != 0) l_Matches[3] = l_Entry->AreaID[3] == GetAreaId(); ///< Comparison of integers of different signs: 'const unsigned int' and 'int32' (aka 'int')

        if (!EvalMatch(l_Matches, l_Entry->AreaLogic))
            return std::pair<bool, std::string>(false, "Failed on AreaID");
    }
    #pragma endregion AreaLogic, AreaID

    #pragma region CurrencyLogic, CurrencyID, CurrencyCount
    if (l_Entry->CurrencyID[0] || l_Entry->CurrencyID[1] || l_Entry->CurrencyID[2] || l_Entry->CurrencyID[3])
    {
        bool l_Matches[4] { true, true, true, true };

        if (l_Entry->CurrencyID[0] != 0) l_Matches[0] = HasCurrency(l_Entry->CurrencyID[0], (!l_Entry->CurrencyCount[0] ? 1 : l_Entry->CurrencyCount[0]));
        if (l_Entry->CurrencyID[1] != 0) l_Matches[1] = HasCurrency(l_Entry->CurrencyID[0], (!l_Entry->CurrencyCount[1] ? 1 : l_Entry->CurrencyCount[1]));
        if (l_Entry->CurrencyID[2] != 0) l_Matches[2] = HasCurrency(l_Entry->CurrencyID[0], (!l_Entry->CurrencyCount[2] ? 1 : l_Entry->CurrencyCount[2]));
        if (l_Entry->CurrencyID[3] != 0) l_Matches[3] = HasCurrency(l_Entry->CurrencyID[0], (!l_Entry->CurrencyCount[3] ? 1 : l_Entry->CurrencyCount[3]));

        if (!EvalMatch(l_Matches, l_Entry->CurrencyLogic))
            return std::pair<bool, std::string>(false, "Failed on CurrencyID");
    }
    #pragma endregion CurrencyLogic, CurrencyID, CurrencyCount

    #pragma region QuestKillID, QuestKillLogic, QuestKillMonster
    if (l_Entry->QuestKillID != 0)
    {
        if (!HasQuest(l_Entry->QuestKillID))
            return std::pair<bool, std::string>(false, "Failed on QuestKillID => dbc(" + std::to_string(l_Entry->QuestKillID) + ") you didn't have quest(" + std::to_string(l_Entry->QuestKillID) + ")");

        auto GetNpcObjectiveID = [](uint32 p_QuestID, uint32 p_NPCID) -> uint32
        {
            Quest const* l_Quest = sObjectMgr->GetQuestTemplate(p_QuestID);

            if (!l_Quest)
                return 0;

            for (auto l_Obective : l_Quest->QuestObjectives)
            {
                if (l_Obective.Type != QUEST_OBJECTIVE_TYPE_NPC)
                    continue;

                if (l_Obective.ObjectID == p_NPCID) ///< Comparison of integers of different signs: 'const unsigned int' and 'int32' (aka 'int')
                    return l_Obective.ID;
            }

            return 0;
        };

        bool l_Matches[4] { true, true, true, true };

        if (l_Entry->QuestKillMonster[0] != 0) l_Matches[0] = GetNpcObjectiveID(l_Entry->QuestKillID, l_Entry->QuestKillMonster[0]) && GetQuestObjectiveCounter(GetNpcObjectiveID(l_Entry->QuestKillID, l_Entry->QuestKillMonster[0]));
        if (l_Entry->QuestKillMonster[1] != 0) l_Matches[1] = GetNpcObjectiveID(l_Entry->QuestKillID, l_Entry->QuestKillMonster[1]) && GetQuestObjectiveCounter(GetNpcObjectiveID(l_Entry->QuestKillID, l_Entry->QuestKillMonster[1]));
        if (l_Entry->QuestKillMonster[2] != 0) l_Matches[2] = GetNpcObjectiveID(l_Entry->QuestKillID, l_Entry->QuestKillMonster[2]) && GetQuestObjectiveCounter(GetNpcObjectiveID(l_Entry->QuestKillID, l_Entry->QuestKillMonster[2]));
        if (l_Entry->QuestKillMonster[3] != 0) l_Matches[3] = GetNpcObjectiveID(l_Entry->QuestKillID, l_Entry->QuestKillMonster[3]) && GetQuestObjectiveCounter(GetNpcObjectiveID(l_Entry->QuestKillID, l_Entry->QuestKillMonster[3]));

        if (!EvalMatch(l_Matches, l_Entry->QuestKillLogic))
            return std::pair<bool, std::string>(false, "Failed on QuestKillMonster");
    }
    #pragma endregion QuestKillID, QuestKillLogic, QuestKillMonster

    /// @TODO : MinExpansionLevel
    /// @TODO : MaxExpansionLevel
    /// @TODO : MinExpansionTier
    /// @TODO : MaxExpansionTier
    /// @OBSOLETE : MinGuildLevel
    /// @OBSOLETE : MaxGuildLevel
    /// @TODO : PhaseUseFlags
    /// @TODO : PhaseID
    /// @TODO : PhaseGroupID

    #pragma region MinAvgItemLevel, MaxAvgItemLevel
    if (l_Entry->MinAvgItemLevel != 0 && GetAverageItemLevelTotal() < (uint32)l_Entry->MinAvgItemLevel)
        return std::pair<bool, std::string>(false, "Failed on MinAvgItemLevel => dbc(" + std::to_string(l_Entry->MinAvgItemLevel) + ") you(" + std::to_string(GetAverageItemLevelTotal()) + ")");
    if (l_Entry->MaxAvgItemLevel != 0 && GetAverageItemLevelTotal() > (uint32)l_Entry->MaxAvgItemLevel)
        return std::pair<bool, std::string>(false, "Failed on MaxAvgItemLevel => dbc(" + std::to_string(l_Entry->MaxAvgItemLevel) + ") you(" + std::to_string(GetAverageItemLevelTotal()) + ")");
    #pragma endregion MinAvgItemLevel, MaxAvgItemLevel
    
    #pragma region MinAvgEquippedItemLevel, MaxAvgItemLevel
    if (l_Entry->MinAvgEquippedItemLevel != 0 && GetAverageItemLevelEquipped() < (uint32)l_Entry->MinAvgEquippedItemLevel)
        return std::pair<bool, std::string>(false, "Failed on MinAvgEquippedItemLevel => dbc(" + std::to_string(l_Entry->MinAvgEquippedItemLevel) + ") you(" + std::to_string(GetAverageItemLevelEquipped()) + ")");
    if (l_Entry->MaxAvgEquippedItemLevel != 0 && GetAverageItemLevelEquipped() > (uint32)l_Entry->MaxAvgEquippedItemLevel)
        return std::pair<bool, std::string>(false, "Failed on MaxAvgEquippedItemLevel => dbc(" + std::to_string(l_Entry->MaxAvgEquippedItemLevel) + ") you(" + std::to_string(GetAverageItemLevelEquipped()) + ")");
    #pragma endregion MinAvgEquippedItemLevel, MaxAvgItemLevel

    /// @TODO : ChrSpecializationIndex
    /// @TODO : ChrSpecializationRole
    /// @TODO : PowerType
    /// @TODO : PowerTypeComp
    /// @TODO : PowerTypeValue

    return std::pair<bool, std::string>(true, "");
}

Creature* Player::GetNPCIfCanInteractWith(uint64 p_Guid, uint32 p_NpcFlagMask)
{
    /// Unit checks
    if (!p_Guid)
        return nullptr;

    if (!IsInWorld())
        return nullptr;

    if (isInFlight())
        return nullptr;

    /// Exist (we need look pets also for some interaction (quest/etc)
    Creature* l_Creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, p_Guid);
    if (!l_Creature)
        return nullptr;

    /// Deathstate checks
    if (!isAlive() && !(l_Creature->GetCreatureTemplate()->type_flags & CreatureTypeFlags::CREATURE_TYPEFLAGS_GHOST))
        return nullptr;

    /// Alive or spirit healer
    if (!l_Creature->isAlive() && !(l_Creature->GetCreatureTemplate()->type_flags & CreatureTypeFlags::CREATURE_TYPEFLAGS_DEAD_INTERACT))
        return nullptr;

    /// Appropriate npc type
    if (p_NpcFlagMask && !l_Creature->HasFlag(EUnitFields::UNIT_FIELD_NPC_FLAGS, p_NpcFlagMask))
    {
        /// Targetted object doesn't have required flag.
        if (m_IsDebugQuestLogs)
            ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_NO_FLAG);

        return nullptr;
    }

    /// Not allow interaction under control, but allow with own pets
    if (l_Creature->GetCharmerGUID())
        return nullptr;

    /// Not enemy
    if (l_Creature->IsHostileTo(this))
        return nullptr;

    /// Not unfriendly
    if (FactionTemplateEntry const* l_FactionTemplate = sFactionTemplateStore.LookupEntry(l_Creature->getFaction()))
    {
        if (l_FactionTemplate->Faction)
        {
            if (FactionEntry const* l_Faction = sFactionStore.LookupEntry(l_FactionTemplate->Faction))
            {
                if (l_Faction->ReputationIndex >= 0 && GetReputationMgr().GetRank(l_Faction) <= ReputationRank::REP_UNFRIENDLY)
                    return nullptr;
            }
        }
    }

    /// Not too far
    bool l_ByPassDist = false;
    if (l_Creature->IsAIEnabled)
        l_ByPassDist = l_Creature->AI()->CanByPassDistanceCheck();

    if (!l_ByPassDist && !l_Creature->IsWithinDistInMap(this, INTERACTION_DISTANCE))
        return nullptr;

    return l_Creature;
}

Creature* Player::GetNPCIfCanInteractWithFlag2(uint64 guid, uint32 npcflagmask)
{
    // unit checks
    if (!guid)
        return NULL;

    if (!IsInWorld())
        return NULL;

    if (isInFlight())
        return NULL;

    // exist (we need look pets also for some interaction (quest/etc)
    Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
    if (!creature)
        return NULL;

    // Deathstate checks
    if (!isAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_GHOST))
        return NULL;

    // alive or spirit healer
    if (!creature->isAlive() && !(creature->GetCreatureTemplate()->type_flags & CREATURE_TYPEFLAGS_DEAD_INTERACT))
        return NULL;

    // appropriate npc type
    if (npcflagmask && !creature->HasFlag(UNIT_FIELD_NPC_FLAGS + 1, npcflagmask))
        return NULL;

    // not allow interaction under control, but allow with own pets
    if (creature->GetCharmerGUID())
        return NULL;

    // not enemy
    if (creature->IsHostileTo(this))
        return NULL;

    // not unfriendly
    if (FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(creature->getFaction()))
        if (factionTemplate->Faction)
            if (FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->Faction))
                if (faction->ReputationIndex >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
                    return NULL;

    // not too far
    if (!creature->IsWithinDistInMap(this, INTERACTION_DISTANCE))
        return NULL;

    return creature;
}

GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, GameobjectTypes type) const
{
    if (GameObject* go = GetMap()->GetGameObject(guid))
    {
        if (go->GetGoType() == type)
        {
            float maxdist;
            switch (type)
            {
                // TODO: find out how the client calculates the maximal usage distance to spellless working
                // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
                case GAMEOBJECT_TYPE_GUILD_BANK:
                case GAMEOBJECT_TYPE_MAILBOX:
                    maxdist = 10.0f;
                    break;
                case GAMEOBJECT_TYPE_FISHINGHOLE:
                    maxdist = 20.0f+CONTACT_DISTANCE;       // max spell range
                    break;
                default:
                    maxdist = INTERACTION_DISTANCE;
                    break;
            }

            if (go->IsWithinDistInMap(this, maxdist))
                return go;

            sLog->outDebug(LOG_FILTER_MAPS, "IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name.c_str(),
                go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
        }
    }
    return NULL;
}

bool Player::IsUnderWater() const
{
    return IsInWater() &&
        GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(), GetPositionY())-2);
}

void Player::SetInWater(bool apply)
{
    if (m_isInWater == apply)
        return;

    //define player in water by opcodes
    //move player's guid into HateOfflineList of those mobs
    //which can't swim and move guid back into ThreatList when
    //on surface.
    //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
    m_isInWater = apply;

    // remove auras that need water/land
    RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);

    getHostileRefManager().updateThreatTables();
}

void Player::SetGameMaster(bool p_On)
{
    if (p_On && !(m_ExtraFlags & PLAYER_EXTRA_GM_ON))
    {
        m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
        setFaction(35);
        SetFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GM);
        SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_ALLOW_CHEAT_SPELLS);

        if (Pet* l_Pet = GetPet())
        {
            l_Pet->setFaction(35);
            l_Pet->getHostileRefManager().setOnlineOfflineState(false);
        }

        RemoveByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP);
        ResetContestedPvP();

        getHostileRefManager().setOnlineOfflineState(false);
        CombatStopWithPets();

        SetPhaseMask(uint32(PHASEMASK_ANYWHERE), false);    // see and visible in all phases
        m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GM, GetSession()->GetSecurity());
    }
    else if (!p_On && m_ExtraFlags & PLAYER_EXTRA_GM_ON)
    {
        m_ExtraFlags &= ~PLAYER_EXTRA_GM_ON;
        setFactionForRace(getRace());
        RemoveFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GM);
        RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_ALLOW_CHEAT_SPELLS);

        if (Pet* l_Pet = GetPet())
        {
            l_Pet->setFaction(getFaction());
            l_Pet->getHostileRefManager().setOnlineOfflineState(true);
        }

        // restore FFA PvP Server state
        if (sWorld->IsFFAPvPRealm())
            SetByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP);

        // restore FFA PvP area state, remove not allowed for GM mounts
        UpdateArea(m_areaUpdateId);

        getHostileRefManager().setOnlineOfflineState(true);
        m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_PLAYER);

        phaseMgr.AddUpdateFlag(PHASE_UPDATE_FLAG_SERVERSIDE_CHANGED);
        phaseMgr.Update();
    }

    UpdateObjectVisibility();
}

void Player::SetGMVisible(bool on)
{
    if (on)
    {
        m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE;         //remove flag
        m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, SEC_PLAYER);
    }
    else
    {
        m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE;          //add flag

        SetAcceptWhispers(false);
        SetGameMaster(true);

        m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GM, GetSession()->GetSecurity());
    }
}

bool Player::IsGroupVisibleFor(Player const* p) const
{
    switch (sWorld->getIntConfig(CONFIG_GROUP_VISIBILITY))
    {
        default: return IsInSameGroupWith(p);
        case 1:  return IsInSameRaidWith(p);
        case 2:  return GetTeam() == p->GetTeam();
    }
}

bool Player::IsInSameGroupWith(Player const* p) const
{
    return p == this || (GetGroup() != NULL &&
        GetGroup() == p->GetGroup() &&
        GetGroup()->SameSubGroup(this, p));
}

///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
/// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
void Player::UninviteFromGroup()
{
    uint32 groupGUID = GetGroupInvite();
    if (!groupGUID)
        return;

    Group* group = sGroupMgr->GetGroupByGUID(groupGUID);
    if (!group)
        return;

    group->RemoveInvite(this);

    if (group->GetMembersCount() <= 1)                       // group has just 1 member => disband
    {
        if (group->IsCreated())
        {
            group->Disband(true);
        }
        else
        {
            group->RemoveAllInvites();
            delete group;
        }
    }
}

void Player::RemoveFromGroup(Group* group, uint64 guid, RemoveMethod method /* = GROUP_REMOVEMETHOD_DEFAULT*/, uint64 kicker /* = 0 */, const char* reason /* = NULL */)
{
    if (group)
    {
        group->RemoveMember(guid, method, kicker, reason);
        group = NULL;<--- Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?
    }
}

void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool recruitAFriend, float group_rate)
{
    WorldPacket data(SMSG_LOG_XP_GAIN);

    ObjectGuid victimGuid = victim ? victim->GetGUID() : 0;
    data.appendPackGUID(victimGuid);
    data << uint32(GivenXP);
    data << uint8(victim ? 0 : 1);                  ///< 00-kill_xp type, 01-non_kill_xp type
    data << uint32(GivenXP + BonusXP);
    data << float(group_rate);                      ///< Group bonus
    data.WriteBit(recruitAFriend);
    data.FlushBits();                               ///< Refer A Friend

    GetSession()->SendPacket(&data);
}

void Player::GiveXP(uint32 xp, Unit* victim, float group_rate)
{
    if (xp < 1)
        return;

    if (!isAlive() && !GetBattlegroundId())
        return;

    if (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_NO_XP_GAIN))
        return;

    if (victim && victim->GetTypeId() == TYPEID_UNIT && !victim->ToCreature()->hasLootRecipient())
        return;

    uint8 level = getLevel();

    sScriptMgr->OnGivePlayerXP(this, xp, victim);

    // Favored experience increase START
    uint32 zone = GetZoneId();
    float favored_exp_mult = 0;
    if ((HasAura(32096) || HasAura(32098)) && (zone == 3483 || zone == 3562 || zone == 3836 || zone == 3713 || zone == 3714))
        favored_exp_mult = 0.05f; // Thrallmar's Favor and Honor Hold's Favor
    xp = uint32(xp * (1 + favored_exp_mult));
    // Favored experience increase END

    // XP to money conversion processed in Player::RewardQuest
    if (level >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
        return;

    // VIP xp reward
    if (GetSession()->IsPremium())
        xp *= 1.15f;

    uint32 bonus_xp = 0;
    bool recruitAFriend = GetsRecruitAFriendBonus(true);

    // RaF does NOT stack with rested experience
    if (recruitAFriend)
        bonus_xp = 2 * xp; // xp + bonus_xp must add up to 3 * xp for RaF; calculation for quests done client-side
    else
        bonus_xp = victim ? GetXPRestBonus(xp) : 0; // XP resting bonus

    SendLogXPGain(xp, victim, bonus_xp, recruitAFriend, group_rate);

    uint32 curXP = GetUInt32Value(PLAYER_FIELD_XP);
    uint32 nextLvlXP = GetUInt32Value(PLAYER_FIELD_NEXT_LEVEL_XP);
    uint32 newXP = curXP + xp + bonus_xp;

    while (newXP >= nextLvlXP && level < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
    {
        newXP -= nextLvlXP;

        if (level < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
            GiveLevel(level + 1);

        level = getLevel();
        nextLvlXP = GetUInt32Value(PLAYER_FIELD_NEXT_LEVEL_XP);
    }

    SetUInt32Value(PLAYER_FIELD_XP, newXP);
}

// Give xp when gathering herbalism and mininh
// Formulas found here : http://www.wowwiki.com/Formulas:Gather_XP
void Player::GiveGatheringXP()
{
    uint32 level = getLevel();
    uint32 gain = 0;

    if (level >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
        return;

    if (level < 50)
        gain = 12.76f * level;
    else if (level > 49 && level < 60)
        gain = 25 * level - 550;
    else if (level > 59 && level < 70)
        gain = 20 * level - 200;
    else if (level > 69 && level < 80)
        gain = 100 * level - 6600;
    else if (level > 79 && level < 85)
        gain = 750 * level - 58250;
    else if (level > 84 && level < 90)
        gain = 1720 * level - 138800; // (7400 - 14280),  Guessed, @TODO : find blizzlike formula (7400 - 14280)
    else if (level > 89 && level < 95)
        gain = -225 * level + 23100;
    else if (level > 94 && level < 100)
        gain = -228 * level + 24512;    ///< Guessed

    float GatheringXpRate = 1;

    if (GetPersonnalXpRate())
        GatheringXpRate = GetPersonnalXpRate();
    else
        GatheringXpRate = sWorld->getRate(RATE_XP_GATHERING);

    gain *= GatheringXpRate;
    GiveXP(gain, nullptr);
}

// Update player to next level
// Current player experience not update (must be update by caller)
void Player::GiveLevel(uint8 level)
{
    uint8 oldLevel = getLevel();
    if (level == oldLevel)
        return;

    PlayerLevelInfo info;
    sObjectMgr->GetPlayerLevelInfo(getRace(), getClass(), level, &info);

    uint32 basehp = 0, basemana = 0;
    sObjectMgr->GetPlayerClassLevelInfo(getClass(), level, basehp, basemana);

    // send levelup info to client
    WorldPacket data(SMSG_LEVELUP_INFO, 100);

    data << uint32(level);
    data << uint32(int32(basehp) - int32(GetCreateHealth()));

    data << uint32(int32(basemana) - int32(GetCreateMana()));
    data << uint32(0);
    data << uint32(0);
    data << uint32(0);
    data << uint32(0);
    data << uint32(0);

    for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)       // Stats loop (0-4)
        data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));

    bool talent = false;

    switch (level)
    {
        case 15:
        case 30:
        case 45:
        case 60:
        case 75:
        case 90:
        case 100:
            talent = true;
            break;
        default:
            break;
    }

    data << uint32(talent);                                 // Has talent

    GetSession()->SendPacket(&data);

    SetUInt32Value(PLAYER_FIELD_NEXT_LEVEL_XP, sObjectMgr->GetXPForLevel(level));

    //update level, max level of skills
    m_Played_time[PLAYED_TIME_LEVEL] = 0;                   // Level Played Time reset

    SetLevel(level);

    // save base values (bonuses already included in stored stats
    for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
        SetCreateStat(Stats(i), info.stats[i]);

    SetCreateHealth(basehp);
    SetCreateMana(basemana);

    InitTalentForLevel();
    InitSpellForLevel();
    InitTaxiNodesForLevel();
    InitGlyphsForLevel();

    UpdateAllStats();
    RescaleAllItemsIfNeeded(true);

    // Refresh amount of all auras (aura which use scaling for basepoint calcul need to be refresh at level up ...)
    AuraApplicationMap const& l_AppliedAuras =  GetAppliedAuras();
    for (AuraApplicationMap::const_iterator i = l_AppliedAuras.begin(); i != l_AppliedAuras.end(); ++i)
        i->second->GetBase()->RecalculateAmountOfEffects(true);

    // set current level health and mana/energy to maximum after applying all mods.
    SetFullHealth();
    SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
    SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
    if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
        SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
    SetPower(POWER_FOCUS, 0);

    // update level to hunter/summon pet
    if (Pet* pet = GetPet())
        pet->SynchronizeLevelWithOwner();

    if (MailLevelReward const* mailReward = sObjectMgr->GetMailLevelReward(level, getRaceMask()))
    {
        //- @TODO: Poor design of mail system
        SQLTransaction trans = CharacterDatabase.BeginTransaction();
        MailDraft(mailReward->mailTemplateId).SendMailTo(trans, this, MailSender(MAIL_CREATURE, mailReward->senderEntry));
        CharacterDatabase.CommitTransaction(trans);
    }

    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);

    PhaseUpdateData phaseUdateData;
    phaseUdateData.AddConditionType(CONDITION_LEVEL);

    phaseMgr.NotifyConditionChanged(phaseUdateData);

    // Refer-A-Friend
/// Commented due to action bar fix, need more research
//     if (GetSession()->GetRecruiterId())
//         if (level < sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL))
//             if (level % 2 == 0)
//             {
//                 ++m_grantableLevels;
//
//                 if (!HasByteFlag(PLAYER_FIELD_LIFETIME_MAX_RANK, PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL, 0x01))
//                     SetByteFlag(PLAYER_FIELD_LIFETIME_MAX_RANK, PLAYER_FIELD_BYTES_OFFSET_RAF_GRANTABLE_LEVEL, 0x01);
//             }

    if (level == 85)
    {
        uint32 idQuest;
        if (GetTeam() == TEAM_ALLIANCE)
        {
            idQuest = 29547;
        }
        else
            idQuest = 29611;

        Quest const* quest = sObjectMgr->GetQuestTemplate(idQuest);
        if (quest)
            AddQuest(quest, NULL);
    }
    else if (level >= 90 && GetQuestStatus(36881) == QUEST_STATUS_NONE)
    {
        if (Quest const* l_Quest = sObjectMgr->GetQuestTemplate(36881)) // Add quest for starting WoD missions and go to Draenor
        {
            if (GetQuestStatus(36881) == QUEST_STATUS_NONE || GetQuestStatus(36881) == QUEST_STATUS_FAILED)
                AddQuest(l_Quest, NULL);
        }
    }

    sScriptMgr->OnPlayerLevelChanged(this, oldLevel);

    if (m_Garrison)
        m_Garrison->OnOwnerLevelChange(level);
}

void Player::InitTalentForLevel()
{
    uint8 level = getLevel();
    // talents base at level diff (talents = level - 9 but some can be used already)
    if (level < 15)
    {
        // Remove all talent points
        if (GetUsedTalentCount() > 0)                           // Free any used talents
        {
            ResetTalents(true);
            SetFreeTalentPoints(0);
        }
    }
    else
    {
        if (level < sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL) || GetSpecsCount() == 0)
        {
            SetSpecsCount(1);
            SetActiveSpec(0);
        }

        uint32 talentPointsForLevel = CalculateTalentsPoints();

        // if used more that have then reset
        if (GetUsedTalentCount() > talentPointsForLevel)
        {
            if (!AccountMgr::IsAdminAccount(GetSession()->GetSecurity()))
                ResetTalents(true);
            else
                SetFreeTalentPoints(0);
        }
        // else update amount of free points
        else
            SetFreeTalentPoints(talentPointsForLevel - GetUsedTalentCount());
    }

    if (!GetSession()->PlayerLoading())
        SendTalentsInfoData(false);                         // update at client
}


void Player::InitSpellForLevel()
{
    std::set<uint32> l_SpellList = sSpellMgr->GetSpellClassList(getClass());

    // Add talent placeholders spells to spelllist
    for (uint32 l_TalentPlaceHolderSpell : sSpellMgr->GetTalentPlaceHoldersSpell())
        l_SpellList.insert(l_TalentPlaceHolderSpell);

    uint8 l_Level = getLevel();
    uint32 l_SpecializationId = GetSpecializationId();

    for (uint32 l_SpellId : l_SpellList)
    {
        SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_SpellId);
        if (!l_SpellInfo)
            continue;

        if (HasSpell(l_SpellId))
            continue;

        if (!l_SpellInfo->SpecializationIdList.empty())
        {
            bool find = false;

            for (uint32 itr : l_SpellInfo->SpecializationIdList)
            if (itr == l_SpecializationId)
                find = true;

            if (!find)
                continue;
        }

        if (!IsSpellFitByClassAndRace(l_SpellId))
            continue;

        // Hack fix - Dual Wield cannot be on MistWeaver monks
        if (l_SpecializationId == SPEC_MONK_MISTWEAVER && (l_SpellId == 674 || l_SpellId == 124146))
            continue;

        // Hack fix - Monks can't get Daggers competance
        if (getClass() == CLASS_MONK && l_SpellId == 1180)
            continue;

        if (l_SpellInfo->SpellLevel <= l_Level)
            learnSpell(l_SpellId, false);
    }

    const std::set<MinorTalentEntry const*>* l_PerkList = sSpellMgr->GetSpecializationPerks(l_SpecializationId);
    if (l_PerkList)
    {
        // perks are starting at level 90
#define PERK_START_LEVEL 90

        float l_LevelDiff = getLevel() - PERK_START_LEVEL;
        float l_Coeff = (MAX_LEVEL - PERK_START_LEVEL) / float(l_PerkList->size());

        if (l_LevelDiff > 0)
        {
            uint8 l_CurrentIndex = floor(((l_LevelDiff - 1.0f) > 0.0f ? (l_LevelDiff - 1.0f) : 0) / l_Coeff);

            for (auto perk : *l_PerkList)
            if (l_CurrentIndex >= perk->orderIndex)
                learnSpell(perk->spellID, false);
        }
    }

    // Aberration, Two Forms, Darkflight, Flayer, Viciousness
    if (getRace() == RACE_WORGEN)
    {
        learnSpell(68976, false);
        learnSpell(68996, false);
        learnSpell(97709, false);
        learnSpell(68992, false);
        learnSpell(68978, false);
        learnSpell(68975, false);
    }
    else
    {
        if (HasSpell(68996))
            removeSpell(68996, false, false);
        if (HasSpell(68976))
            removeSpell(68976, false, false);
        if (HasSpell(97709))
            removeSpell(97709, false, false);
        if (HasSpell(68992))
            removeSpell(68992, false, false);
        if (HasSpell(68978))
            removeSpell(68978, false, false);
        if (HasSpell(68975))
            removeSpell(68975, false, false);
    }

    if (getRace() == Races::RACE_NIGHTELF)
        learnSpell(154748, false);

    // Worgen players are automatically granted Apprentice Riding at level 20, as well, due to their racial ability Running Wild.
    // http://www.wowhead.com/spell=33388
    if (l_Level >= 20 && getRace() == RACE_WORGEN)
    {
        learnSpell(87840, false); // Running Wild
        learnSpell(33388, false); // Apprentice Riding
    }
    else
    {
        // Only for Worgens with level >= 20
        if (HasSpell(87840))
            removeSpell(87840, false, false);

        // Some spells allowing flying mounts in some maps
        if (HasSpell(115913) && getLevel() < 90)
            removeSpell(115913, false, false);
        if (HasSpell(90267) && getLevel() < 60)
            removeSpell(90267, false, false);
    }

    // Fix Pick Lock update at each level
    if (HasSpell(1804) && getLevel() > 20)
        SetSkill(921, GetSkillStep(921), (getLevel() * 5), (getLevel() * 5));

    /// Missing mining skill (shop issue)
    if (GetSkillValue(SkillType::SKILL_MINING) >= 700 && !HasSpell(158754))
        learnSpell(158754, false);
}

void Player::RemoveSpecializationSpells()
{
    std::list<uint32> spellToRemove;

    for (auto itr : GetSpellMap())
    {
        SpellInfo const* spell = sSpellMgr->GetSpellInfo(itr.first);
        if (spell && !spell->SpecializationIdList.empty()
            && spell->Id != 674)    ///< Ambidextrie hackfix, removed at spec switch (rogue)
            spellToRemove.push_back(itr.first);
    }

    for (uint32 i = 0; i < sMinorTalentStore.GetNumRows(); i++)
        if (MinorTalentEntry const* minorTalent = sMinorTalentStore.LookupEntry(i))
            if (HasSpell(minorTalent->spellID))
                spellToRemove.push_back(minorTalent->spellID);

    spellToRemove.push_back(48517); // Lunar eclipse
    spellToRemove.push_back(48518); // Solar eclipse
    spellToRemove.push_back(107095); // Lunar eclipse (overrider)

    for (auto itr : spellToRemove)
        removeSpell(itr);
}

void Player::InitStatsForLevel(bool reapplyMods)
{
    if (reapplyMods)                                        //reapply stats values only on .reset stats (level) command
        _RemoveAllStatBonuses();

    uint32 basehp = 0, basemana = 0;
    sObjectMgr->GetPlayerClassLevelInfo(getClass(), getLevel(), basehp, basemana);

    PlayerLevelInfo info;
    sObjectMgr->GetPlayerLevelInfo(getRace(), getClass(), getLevel(), &info);

    SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL));
    SetUInt32Value(PLAYER_FIELD_NEXT_LEVEL_XP, sObjectMgr->GetXPForLevel(getLevel()));

    // reset before any aura state sources (health set/aura apply)
    SetUInt32Value(UNIT_FIELD_AURA_STATE, 0);

    // set default cast time multiplier
    SetFloatValue(UNIT_FIELD_MOD_CASTING_SPEED, 1.0f);
    SetFloatValue(UNIT_FIELD_MOD_SPELL_HASTE, 1.0f);
    SetFloatValue(UNIT_FIELD_MOD_HASTE, 1.0f);
    SetFloatValue(UNIT_FIELD_MOD_HASTE_REGEN, 1.0f);
    SetFloatValue(UNIT_FIELD_MOD_RANGED_HASTE, 1.0f);
    SetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER, 0.0f);
    SetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER, 0.0f);

    // reset size before reapply auras
    SetObjectScale(1.0f);

    // save base values (bonuses already included in stored stats
    for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
        SetCreateStat(Stats(i), info.stats[i]);

    for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i)
        SetStat(Stats(i), info.stats[i]);

    SetCreateHealth(basehp);

    //set create powers
    SetCreateMana(basemana);

    SetArmor(int32(m_createStats[STAT_AGILITY]*2));

    InitStatBuffMods();

    //reset rating fields values
    for (uint16 index = PLAYER_FIELD_COMBAT_RATINGS; index < PLAYER_FIELD_COMBAT_RATINGS + MAX_COMBAT_RATING; ++index)
        SetUInt32Value(index, 0);

    SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS, 0);
    SetFloatValue(PLAYER_FIELD_MOD_HEALING_PERCENT, 1.0f);
    SetFloatValue(PLAYER_FIELD_MOD_HEALING_DONE_PERCENT, 1.0f);
    SetFloatValue(PLAYER_FIELD_MOD_PERIODIC_HEALING_DONE_PERCENT, 1.0f);
    for (uint8 i = 0; i < 7; ++i)
    {
        SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
        SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
        SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PERCENT+i, 1.00f);
    }

    SetFloatValue(PLAYER_FIELD_MOD_SPELL_POWER_PERCENT, 1.0f);

    //reset attack power, damage and attack speed fields
    SetFloatValue(UNIT_FIELD_ATTACK_ROUND_BASE_TIME, 2000.0f);
    SetFloatValue(UNIT_FIELD_ATTACK_ROUND_BASE_TIME + 1, 2000.0f); // offhand attack time
    SetFloatValue(UNIT_FIELD_RANGED_ATTACK_ROUND_BASE_TIME, 2000.0f);

    SetFloatValue(UNIT_FIELD_MIN_DAMAGE, 0.0f);
    SetFloatValue(UNIT_FIELD_MAX_DAMAGE, 0.0f);
    SetFloatValue(UNIT_FIELD_MIN_OFF_HAND_DAMAGE, 0.0f);
    SetFloatValue(UNIT_FIELD_MAX_OFF_HAND_DAMAGE, 0.0f);
    SetFloatValue(UNIT_FIELD_MIN_RANGED_DAMAGE, 0.0f);
    SetFloatValue(UNIT_FIELD_MAX_RANGED_DAMAGE, 0.0f);
    for (uint8 l_WeaponAttackType = WeaponAttackType::BaseAttack; l_WeaponAttackType < WeaponAttackType::MaxAttack; l_WeaponAttackType++)
    {
        SetFloatValue(PLAYER_FIELD_WEAPON_DMG_MULTIPLIERS       + l_WeaponAttackType, 1.0f);
        SetFloatValue(PLAYER_FIELD_WEAPON_ATK_SPEED_MULTIPLIERS + l_WeaponAttackType, 1.0f);
    }

    SetInt32Value(UNIT_FIELD_ATTACK_POWER,            0);
    SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER, 0.0f);
    SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER,     0);
    SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER, 0.0f);

    // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
    SetFloatValue(PLAYER_FIELD_CRIT_PERCENTAGE, 0.0f);
    SetFloatValue(PLAYER_FIELD_OFFHAND_CRIT_PERCENTAGE, 0.0f);
    SetFloatValue(PLAYER_FIELD_RANGED_CRIT_PERCENTAGE, 0.0f);

    for (uint8 l_I = 0; l_I < PlayerAvgItemLevelOffsets::MaxAvgItemLevel; l_I++)
        SetFloatValue(PLAYER_FIELD_AVG_ITEM_LEVEL + l_I, 0.0f);

    // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
    for (uint8 i = 0; i < 7; ++i)
        SetFloatValue(PLAYER_FIELD_SPELL_CRIT_PERCENTAGE+i, 0.0f);

    SetFloatValue(PLAYER_FIELD_PARRY_PERCENTAGE, 0.0f);
    SetFloatValue(PLAYER_FIELD_BLOCK_PERCENTAGE, 0.0f);

    // Static 30% damage blocked
    SetUInt32Value(PLAYER_FIELD_SHIELD_BLOCK, 30);

    // Dodge percentage
    SetFloatValue(PLAYER_FIELD_DODGE_PERCENTAGE, 0.0f);

    // set armor (resistance 0) to original value (create_agility*2)
    SetArmor(int32(m_createStats[STAT_AGILITY]*2));
    SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
    SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
    // set other resistance to original value (0)
    for (uint8 i = 1; i < MAX_SPELL_SCHOOL; ++i)
    {
        SetResistance(SpellSchools(i), 0);
        SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
        SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
    }

    SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE, 0);
    SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE, 0);
    for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
    {
        SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i, 0);
        SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i, 0.0f);
    }
    // Reset no reagent cost field
    for (uint8 i = 0; i < 3; ++i)
        SetUInt32Value(PLAYER_FIELD_NO_REAGENT_COST_MASK + i, 0);
    // Init data for form but skip reapply item mods for form
    InitDataForForm(reapplyMods);

    // save new stats
    for (uint8 i = POWER_MANA; i < MAX_POWERS; ++i)
        SetMaxPower(Powers(i), GetCreatePowers(Powers(i)));

    SetMaxHealth(basehp);                     // stamina bonus will applied later

    // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
    SetUInt32Value(UNIT_FIELD_MOUNT_DISPLAY_ID, 0);

    // cleanup unit flags (will be re-applied if need at aura load).
    RemoveFlag(UNIT_FIELD_FLAGS,
        UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
        UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC  | UNIT_FLAG_LOOTING          |
        UNIT_FLAG_PET_IN_COMBAT  | UNIT_FLAG_SILENCED     | UNIT_FLAG_PACIFIED         |
        UNIT_FLAG_STUNNED        | UNIT_FLAG_IN_COMBAT    | UNIT_FLAG_DISARMED         |
        UNIT_FLAG_CONFUSED       | UNIT_FLAG_FLEEING      | UNIT_FLAG_NOT_SELECTABLE   |
        UNIT_FLAG_SKINNABLE      | UNIT_FLAG_MOUNT        | UNIT_FLAG_TAXI_FLIGHT      );
    SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);   // must be set

    SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);// must be set

    // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
    RemoveFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_ALLOW_ONLY_ABILITY);

    RemoveStandFlags(UNIT_STAND_FLAGS_ALL);                 // one form stealth modified bytes
    RemoveByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);

    // restore if need some important flags
    SetUInt32Value(PLAYER_FIELD_OVERRIDE_SPELLS_ID, 0);                 // flags empty by default
    //SetUInt32Value(PLAYER_FIELD_AURA_VISION, 0);                        // flags empty by default


    if (reapplyMods)                                        // reapply stats values only on .reset stats (level) command
        _ApplyAllStatBonuses();

    // set current level health and mana/energy to maximum after applying all mods.
    SetFullHealth();
    SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
    SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));

    if (GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
        SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));

    SetPower(POWER_FOCUS, GetMaxPower(POWER_FOCUS));
    SetPower(POWER_RUNIC_POWER, 0);
    SetPower(POWER_CHI, 0);
    SetPower(POWER_SOUL_SHARDS, 100);
    SetPower(POWER_DEMONIC_FURY, 200);
    SetPower(POWER_BURNING_EMBERS, 10);
    SetPower(POWER_SHADOW_ORB, 0);
    SetPower(POWER_ECLIPSE, 0);

    // update level to hunter/summon pet
    if (Pet* pet = GetPet())
        pet->SynchronizeLevelWithOwner();
}

void Player::SendKnownSpells()
{
    uint32 l_SpellCount = 0;

    WorldPacket l_Data(SMSG_SEND_KNOWN_SPELLS, 25 * 1024);

    l_Data.WriteBit(1);
    l_Data.FlushBits();

    l_Data << uint32(l_SpellCount);

    // spell count placeholder
    for (PlayerSpellMap::const_iterator l_It = m_spells.begin(); l_It != m_spells.end(); ++l_It)
    {
        if (!l_It->second)
            continue;

        if (l_It->second->state == PlayerSpellState::PLAYERSPELL_REMOVED
            || l_It->second->state == PlayerSpellState::PLAYERSPELL_TEMPORARY)
            continue;

        if (!l_It->second->active || l_It->second->disabled)
            continue;

        l_Data << uint32(l_It->first);

        ++l_SpellCount;
    }

    l_Data.wpos(1);
    l_Data << uint32(l_SpellCount);

    GetSession()->SendPacket(&l_Data);
}

void Player::RemoveMail(uint32 id)
{
    for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
    {
        if ((*itr)->messageID == id)
        {
            //do not delete item, because Player::removeMail() is called when returning mail to sender.
            m_mail.erase(itr);
            return;
        }
    }
}

void Player::SendMailResult(uint32 p_MailID, MailResponseType p_MailAction, MailResponseResult p_MailError, uint32 p_EquipError, uint32 p_ItemGuid, uint32 p_ItemCount)
{
    WorldPacket l_Data(SMSG_SEND_MAIL_RESULT, 4 * 6);

    l_Data << uint32(p_MailID);
    l_Data << uint32(p_MailAction);
    l_Data << uint32(p_MailError);
    l_Data << uint32(p_EquipError);
    l_Data << uint32(p_ItemGuid);
    l_Data << uint32(p_ItemCount);

    GetSession()->SendPacket(&l_Data);
}

void Player::SendNewMail()
{
    // deliver undelivered mail
    WorldPacket l_Data(SMSG_RECEIVED_MAIL, 4);
    l_Data << (uint32)0;

    GetSession()->SendPacket(&l_Data);
}

void Player::UpdateNextMailTimeAndUnreads()
{
    // calculate next delivery time (min. from non-delivered mails
    // and recalculate unReadMail
    time_t cTime = time(NULL);
    m_nextMailDelivereTime = 0;
    unReadMails = 0;
    for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
    {
        if ((*itr)->deliver_time > cTime)
        {
            if (!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
                m_nextMailDelivereTime = (*itr)->deliver_time;
        }
        else if (((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
            ++unReadMails;
    }
}

void Player::AddNewMailDeliverTime(time_t deliver_time)
{
    if (deliver_time <= time(NULL))                          // ready now
    {
        ++unReadMails;
        SendNewMail();
    }
    else                                                    // not ready and no have ready mails
    {
        if (!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
            m_nextMailDelivereTime = deliver_time;
    }
}

bool Player::AddTalent(uint32 spellId, uint8 spec, bool learning)
{
    SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
    if (!spellInfo)
        return false;

    if (!SpellMgr::IsSpellValid(spellInfo, this, false))
        return false;

    PlayerTalentMap::iterator itr = GetTalentMap(spec)->find(spellId);
    if (itr != GetTalentMap(spec)->end())
        itr->second->state = PLAYERSPELL_UNCHANGED;
    else
    {

        PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
        PlayerTalent* newtalent = new PlayerTalent();

        newtalent->state = state;
        newtalent->spec = spec;

        (*GetTalentMap(spec))[spellId] = newtalent;
        return true;
    }
    return false;
}

bool Player::addSpell(uint32 spellId, bool active, bool learning, bool dependent, bool disabled, bool loading /*= false*/, bool p_IsMountFavorite, bool p_LearnBattlePet, bool p_FromShopItem)
{
    SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId);
    if (!spellInfo)
        return false;

    if (!SpellMgr::IsSpellValid(spellInfo, this, false))
        return false;

    if (sSpellMgr->IsSpellForbidden(spellId) && !isGameMaster() && sWorld->getBoolConfig(CONFIG_SPELL_FORBIDDEN))
    {
        std::string banString;
        banString = "Auto-ban for spell cheat ";
        char buff[2048];

        sprintf(buff, "(spellId : %u)", (uint32)spellId);
        banString += buff;
        sWorld->BanAccount(BAN_CHARACTER, GetName(), "-1", banString, "Auto-Ban");
        return false;
    }

    /// Prevent load of incorrect passives / spells
    if (!spellInfo->SpecializationIdList.empty() && std::find(spellInfo->SpecializationIdList.begin(), spellInfo->SpecializationIdList.end(), GetSpecializationId()) == spellInfo->SpecializationIdList.end()
        && spellInfo->Id != 674)    ///< Ambidextrie hackfix, removed at spec switch (rogue))
        return false;

    /// - Remove non authorized spell (learned when system was buggede)
    if ((spellInfo->AttributesEx7 & SPELL_ATTR7_HORDE_ONLY && (getRaceMask() & RACEMASK_HORDE) == 0)
        || (spellInfo->AttributesEx7 & SPELL_ATTR7_ALLIANCE_ONLY && (getRaceMask() & RACEMASK_ALLIANCE) == 0))
        return false;

    // Validate profession
    if (loading)
    {
        SkillLineAbilityMapBounds spellBounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellInfo->Id);
        for (SkillLineAbilityMap::const_iterator spell_idx = spellBounds.first; spell_idx != spellBounds.second; ++spell_idx)
        {
            if (!IsProfessionSkill(spell_idx->second->skillId))
                continue;

            if (!HasSkill(spell_idx->second->skillId))
                disabled = true;
        }
    }

    PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;

    bool dependent_set = false;
    bool disabled_case = false;
    bool superceded_old = false;

    PlayerSpellMap::iterator itr = m_spells.find(spellId);

    // Remove temporary spell if found to prevent conflicts
    if (itr != m_spells.end() && itr->second->state == PLAYERSPELL_TEMPORARY)
        RemoveTemporarySpell(spellId);
    else if (itr != m_spells.end())
    {
        uint32 next_active_spell_id = 0;
        // fix activate state for non-stackable low rank (and find next spell for !active case)
        if (!spellInfo->IsStackableWithRanks() && spellInfo->IsRanked())
        {
            if (uint32 next = sSpellMgr->GetNextSpellInChain(spellId))
            {
                if (HasSpell(next))
                {
                    // high rank already known so this must !active
                    active = false;
                    next_active_spell_id = next;
                }
            }
        }

        // not do anything if already known in expected state
        if (itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
            itr->second->dependent == dependent && itr->second->disabled == disabled)
        {
            if (!IsInWorld() && !learning)                   // explicitly load from DB and then exist in it already and set correctly
                itr->second->state = PLAYERSPELL_UNCHANGED;

            return false;
        }

        // dependent spell known as not dependent, overwrite state
        if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
        {
            itr->second->dependent = dependent;
            if (itr->second->state != PLAYERSPELL_NEW)
                itr->second->state = PLAYERSPELL_CHANGED;
            dependent_set = true;
        }

        // update active state for known spell
        if (itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
        {
            itr->second->active = active;

            if (!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
                itr->second->state = PLAYERSPELL_UNCHANGED;
            else if (itr->second->state != PLAYERSPELL_NEW)
                itr->second->state = PLAYERSPELL_CHANGED;

            if (active)
            {
                if (spellInfo->IsPassive() && IsNeedCastPassiveSpellAtLearn(spellInfo))
                    CastSpell (this, spellId, true);
            }
            else if (IsInWorld())
            {
                if (next_active_spell_id)
                {
                    // update spell ranks in spellbook and action bar
                    WorldPacket l_Data(SMSG_SUPERCEDED_SPELL);
                    l_Data << uint32(1);
                    l_Data << uint32(1);
                    l_Data << uint32(next_active_spell_id);
                    l_Data << uint32(spellId);
                    GetSession()->SendPacket(&l_Data);
                }
                else
                {
                    WorldPacket data(SMSG_UNLEARNED_SPELLS, 4 + 4);
                    data << uint32(1);  // Count spells, always one by one
                    data << uint32(spellId);
                    data.WriteBit(0);   ///< Unk Wod
                    GetSession()->SendPacket(&data);
                }
            }

            return active;                                  // learn (show in spell book if active now)
        }

        if (itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
        {
            if (itr->second->state != PLAYERSPELL_NEW)
                itr->second->state = PLAYERSPELL_CHANGED;
            itr->second->disabled = disabled;

            if (disabled)
                return false;

            disabled_case = true;
        }
        else switch (itr->second->state)
        {
            case PLAYERSPELL_UNCHANGED:                     // known saved spell
                return false;
            case PLAYERSPELL_REMOVED:                       // re-learning removed not saved spell
            {
                delete itr->second;
                m_spells.erase(itr);
                state = PLAYERSPELL_CHANGED;
                break;                                      // need re-add
            }
            default:                                        // known not saved yet spell (new or modified)
            {
                // can be in case spell loading but learned at some previous spell loading
                if (!IsInWorld() && !learning && !dependent_set)
                    itr->second->state = PLAYERSPELL_UNCHANGED;

                return false;
            }
        }
    }

    if (!disabled_case) // skip new spell adding if spell already known (disabled spells case)
    {
        // non talent spell: learn low ranks (recursive call)
        if (uint32 prev_spell = sSpellMgr->GetPrevSpellInChain(spellId))
        {
            if (!IsInWorld() || disabled)                    // at spells loading, no output, but allow save
                addSpell(prev_spell, active, true, true, disabled);
            else                                            // at normal learning
                learnSpell(prev_spell, true);
        }

        PlayerSpell* newspell = new PlayerSpell;
        newspell->state           = state;
        newspell->active          = active;
        newspell->dependent       = dependent;
        newspell->disabled        = disabled;
        newspell->IsMountFavorite = p_IsMountFavorite;
        newspell->FromShopItem    = p_FromShopItem;

        // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
        if (newspell->active && !newspell->disabled && !spellInfo->IsStackableWithRanks() && spellInfo->IsRanked() != 0)
        {
            WorldPacket l_Data(SMSG_SUPERCEDED_SPELL);

            uint32 bitCount = 0;
            ByteBuffer l_DataBuffer;

            for (PlayerSpellMap::iterator l_Iter = m_spells.begin(); l_Iter != m_spells.end(); ++l_Iter)
            {
                if (l_Iter->second->state == PLAYERSPELL_REMOVED)
                    continue;

                SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_Iter->first);
                if (!l_SpellInfo)
                    continue;

                if (spellInfo->IsDifferentRankOf(l_SpellInfo))
                {
                    if (l_Iter->second->active)
                    {
                        if (spellInfo->IsHighRankOf(l_SpellInfo))
                        {
                            if (IsInWorld())                 // not send spell (re-/over-)learn packets at loading
                            {
                                bitCount++;
                                l_DataBuffer << uint32(spellId);
                                l_DataBuffer << uint32(l_Iter->first);
                            }

                            // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
                            l_Iter->second->active = false;
                            if (l_Iter->second->state != PLAYERSPELL_NEW)
                                l_Iter->second->state = PLAYERSPELL_CHANGED;
                            superceded_old = true;          // new spell replace old in action bars and spell book.
                        }
                        else
                        {
                            if (IsInWorld())                 // not send spell (re-/over-)learn packets at loading
                            {
                                bitCount++;
                                l_DataBuffer << uint32(l_Iter->first);
                                l_DataBuffer << uint32(spellId);
                            }

                            // mark new spell as disable (not learned yet for client and will not learned)
                            newspell->active = false;
                            if (newspell->state != PLAYERSPELL_NEW)
                                newspell->state = PLAYERSPELL_CHANGED;
                        }
                    }
                }
            }

            l_Data << uint32(bitCount);
            l_Data << uint32(bitCount);

            if (l_DataBuffer.size())
                l_Data.append(l_DataBuffer);

            GetSession()->SendPacket(&l_Data);
        }

        m_spells[spellId] = newspell;

        /// WoD Custom Fix : Firebolt just for Fire specialization
        if (spellId == 133 && GetSpecializationId() != SPEC_MAGE_FIRE)
            newspell->disabled = true;

        // return false if spell disabled
        if (newspell->disabled)
            return false;
    }

    // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
    // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
    if (!loading && sSpellMgr->IsTalent(spellInfo->Id) && spellInfo->HasEffect(SPELL_EFFECT_LEARN_SPELL))
    {
        // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
        CastSpell(this, spellId, true);
    }
    // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
    else if (spellInfo->IsPassive())
    {
        if (IsNeedCastPassiveSpellAtLearn(spellInfo))
            CastSpell(this, spellId, true);
    }
    else if (spellInfo->HasEffect(SPELL_EFFECT_SKILL_STEP))
    {
        CastSpell(this, spellId, true);
        return false;
    }

    // update used talent points count
    if (sSpellMgr->IsTalent(spellInfo->Id))
    {
        SetUsedTalentCount(GetUsedTalentCount() + 1);
        SetFreeTalentPoints(GetFreeTalentPoints() -1);
        CastPassiveTalentSpell(spellInfo->Id);
    }

    // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
    if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
    {
        if (spellInfo->IsPrimaryProfessionFirstRank())
            SetFreePrimaryProfessions(freeProfs-1);
    }

    // Add BattlePet
    if (learning && !dependent && p_LearnBattlePet)
    {
        for (uint32 speciesId = 0; speciesId != sBattlePetSpeciesStore.GetNumRows(); ++speciesId)
        {
            BattlePetSpeciesEntry const* speciesInfo = sBattlePetSpeciesStore.LookupEntry(speciesId);
            if (!speciesInfo || speciesInfo->spellId != spellId)
                continue;

            BattlePet pet;
            pet.Slot = PETBATTLE_NULL_SLOT;
            pet.NameTimeStamp = 0;
            pet.Species = speciesInfo->id;
            pet.DisplayModelID = 0;
            pet.Flags = 0;

            if (BattlePetTemplate const* temp = sObjectMgr->GetBattlePetTemplate(speciesInfo->id))
            {
                pet.Breed = temp->Breed;
                pet.Quality = temp->Quality;
                pet.Level = temp->Level;
            }
            else
            {
                pet.Breed = 3;
                pet.Quality = BATTLEPET_QUALITY_COMMON;
                pet.Level = 1;
            }

            // Calculate XP for level
            pet.XP = 0;
            if (pet.Level > 1 && pet.Level < 100)
                pet.XP = sGtBattlePetXPStore.LookupEntry(pet.Level - 2)->value * sGtBattlePetXPStore.LookupEntry(100 + pet.Level - 2)->value;

            // Calculate stats
            pet.UpdateStats();
            pet.Health = pet.InfoMaxHealth;

            pet.AddToPlayer(this);
            ReloadPetBattles();
            break;
        }
    }

    // add dependent skills
    uint16 maxskill     = GetMaxSkillValueForLevel();

    SpellLearnSkillNode const* spellLearnSkill = sSpellMgr->GetSpellLearnSkill(spellId);

    SkillLineAbilityMapBounds skill_bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellId);

    if (spellLearnSkill)
    {
        uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
        uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);

        if (skill_value < spellLearnSkill->value)
            skill_value = spellLearnSkill->value;

        if (skill_value < 525)
        {
            switch (spellLearnSkill->skill)
            {
                case SKILL_WAY_OF_GRILL:
                case SKILL_WAY_OF_WOK:
                case SKILL_WAY_OF_POT:
                case SKILL_WAY_OF_STEAMER:
                case SKILL_WAY_OF_OVEN:
                case SKILL_WAY_OF_BREW:
                    skill_value = 525;
                    break;
            }
        }

        uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;

        if (skill_max_value < new_skill_max_value)
            skill_max_value = new_skill_max_value;

        SetSkill(spellLearnSkill->skill, spellLearnSkill->step, skill_value, skill_max_value);
    }
    else
    {
        // not ranked skills
        for (SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
        {
            SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
            if (!pSkill)
                continue;

            if (HasSkill(pSkill->id))
                continue;

            if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
                // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
                ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0))
            {
                switch (GetSkillRangeType(pSkill, _spell_idx->second->racemask != 0))
                {
                    case SKILL_RANGE_LANGUAGE:
                        SetSkill(pSkill->id, GetSkillStep(pSkill->id), 300, 300);
                        break;
                    case SKILL_RANGE_LEVEL:
                        SetSkill(pSkill->id, GetSkillStep(pSkill->id), 1, GetMaxSkillValueForLevel());
                        break;
                    case SKILL_RANGE_MONO:
                        SetSkill(pSkill->id, GetSkillStep(pSkill->id), 1, 1);
                        break;
                    default:
                        break;
                }
            }
        }
    }

    // learn dependent spells
    SpellLearnSpellMapBounds spell_bounds = sSpellMgr->GetSpellLearnSpellMapBounds(spellId);

    for (SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
    {
        if (!itr2->second.autoLearned)
        {
            if (!IsInWorld() || !itr2->second.active)       // at spells loading, no output, but allow save
                addSpell(itr2->second.spell, itr2->second.active, true, true, false);
            else                                            // at normal learning
                learnSpell(itr2->second.spell, true);
        }
    }

    if (!GetSession()->PlayerLoading())
    {
        // not ranked skills
        for (SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
        {
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE, _spell_idx->second->skillId);
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS, _spell_idx->second->skillId);
        }

        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL, spellId);
    }

    // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
    return active && !disabled && !superceded_old;
}

void Player::AddTemporarySpell(uint32 spellId)
{
    PlayerSpellMap::iterator itr = m_spells.find(spellId);
    // spell already added - do not do anything
    if (itr != m_spells.end())
        return;
    PlayerSpell* newspell = new PlayerSpell;
    newspell->state     = PLAYERSPELL_TEMPORARY;
    newspell->active    = true;
    newspell->dependent = false;
    newspell->disabled  = false;
    m_spells[spellId]   = newspell;
}

void Player::RemoveTemporarySpell(uint32 spellId)
{
    PlayerSpellMap::iterator itr = m_spells.find(spellId);
    // spell already not in list - do not do anything
    if (itr == m_spells.end())
        return;
    // spell has other state than temporary - do not change it
    if (itr->second->state != PLAYERSPELL_TEMPORARY)
        return;
    delete itr->second;
    m_spells.erase(itr);
}

bool Player::IsNeedCastPassiveSpellAtLearn(SpellInfo const* spellInfo) const
{
    // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
    // talent dependent passives activated at form apply have proper stance data
    ShapeshiftForm form = GetShapeshiftForm();

    bool need_cast = (!spellInfo->Stances || (form && (spellInfo->Stances & (UI64LIT(1) << (form - 1)))) ||
        (!form && (spellInfo->AttributesEx2 & SPELL_ATTR2_NOT_NEED_SHAPESHIFT)));

    //Check CasterAuraStates
    return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraStateType(spellInfo->CasterAuraState)));
}

void Player::learnSpell(uint32 p_SpellId, bool dependent, bool p_FromItemShop)
{
    PlayerSpellMap::iterator l_Itr = m_spells.find(p_SpellId);

    bool l_Disabled = (l_Itr != m_spells.end()) ? l_Itr->second->disabled : false;
    bool l_Active = l_Disabled ? l_Itr->second->active : true;

    bool l_Learning = addSpell(p_SpellId, l_Active, true, dependent, false, false, false, true, p_FromItemShop);

    // prevent duplicated entires in spell book, also not send if not in world (loading)
    if (l_Learning && IsInWorld())
    {
        bool l_SuppressMessaging = false;
        ;
        TalentsPlaceHoldersSpell l_PlacesHoldersSpell = sSpellMgr->GetTalentPlaceHoldersSpell();
        if (l_PlacesHoldersSpell.find(p_SpellId) != l_PlacesHoldersSpell.end())
            l_SuppressMessaging = true;

        WorldPacket l_Data(SMSG_LEARNED_SPELL);
        l_Data << uint32(1);                        ///< count of spell_id to send.
        l_Data << uint32(p_SpellId);                ///< SpellId
        l_Data.WriteBit(l_SuppressMessaging);       ///< SuppressMessaging
        l_Data.FlushBits();
        GetSession()->SendPacket(&l_Data);

        sScriptMgr->OnPlayerSpellLearned(this, p_SpellId);
    }

    // learn all disabled higher ranks and required spells (recursive)
    if (l_Disabled)
    {
        if (uint32 l_NextSpell = sSpellMgr->GetNextSpellInChain(p_SpellId))
        {
            PlayerSpellMap::iterator l_Iter = m_spells.find(l_NextSpell);
            if (l_Iter != m_spells.end() && l_Iter->second->disabled)
                learnSpell(l_NextSpell, false);
        }

        SpellsRequiringSpellMapBounds l_SpellsRequiringSpell = sSpellMgr->GetSpellsRequiringSpellBounds(p_SpellId);
        for (SpellsRequiringSpellMap::const_iterator l_Itr2 = l_SpellsRequiringSpell.first; l_Itr2 != l_SpellsRequiringSpell.second; ++l_Itr2)
        {
            PlayerSpellMap::iterator l_Iter2 = m_spells.find(l_Itr2->second);
            if (l_Iter2 != m_spells.end() && l_Iter2->second->disabled)
                learnSpell(l_Itr2->second, false);
        }
    }
}

void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank)
{
    PlayerSpellMap::iterator itr = m_spells.find(spell_id);
    if (itr == m_spells.end())
        return;

    if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled) || itr->second->state == PLAYERSPELL_TEMPORARY)
        return;

    // unlearn non talent higher ranks (recursive)
    if (uint32 nextSpell = sSpellMgr->GetNextSpellInChain(spell_id))
    {
        if (HasSpell(nextSpell)/* && !GetTalentSpellPos(nextSpell)*/)
            removeSpell(nextSpell, disabled, false);
    }
    //unlearn spells dependent from recently removed spells
    SpellsRequiringSpellMapBounds spellsRequiringSpell = sSpellMgr->GetSpellsRequiringSpellBounds(spell_id);
    for (SpellsRequiringSpellMap::const_iterator itr2 = spellsRequiringSpell.first; itr2 != spellsRequiringSpell.second; ++itr2)
        removeSpell(itr2->second, disabled);

    // re-search, it can be corrupted in prev loop
    itr = m_spells.find(spell_id);
    if (itr == m_spells.end())
        return;                                             // already unleared

    bool giveTalentPoints = disabled || !itr->second->disabled;

    bool cur_active    = itr->second->active;
    bool cur_dependent = itr->second->dependent;

    if (disabled)
    {
        itr->second->disabled = disabled;
        if (itr->second->state != PLAYERSPELL_NEW)
            itr->second->state = PLAYERSPELL_CHANGED;
    }
    else
    {
        if (itr->second->state == PLAYERSPELL_NEW)
        {
            delete itr->second;
            m_spells.erase(itr);
        }
        else
            itr->second->state = PLAYERSPELL_REMOVED;
    }

    RemoveOwnedAura(spell_id, GetGUID());

    // remove pet auras
    for (uint8 i = 0; i < SpellEffIndex::MAX_EFFECTS; ++i)
        if (PetAura const* petSpell = sSpellMgr->GetPetAura(spell_id, i))
            RemovePetAura(petSpell);

    uint32 talentCosts = sSpellMgr->IsTalent(spell_id) ? 1 : 0;

    // free talent points
    if (talentCosts > 0 && giveTalentPoints)
    {
        if (talentCosts < GetUsedTalentCount())
        {
            SetUsedTalentCount(GetUsedTalentCount() - talentCosts);
            SetFreeTalentPoints(GetFreeTalentPoints() + 1);
        }
        else
        {
            SetUsedTalentCount(0);
            SetFreeTalentPoints(CalculateTalentsPoints());
        }
    }

    // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
    SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id);
    if (!spellInfo)
        return;

    if (spellInfo->IsPrimaryProfessionFirstRank())
    {
        uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
        if (freeProfs <= sWorld->getIntConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
            SetFreePrimaryProfessions(freeProfs);
    }

    RemovePassiveTalentSpell(spellInfo);

    /// Remove areatrigger
    std::list<AreaTrigger*> l_AreaTriggerList;
    GetAreaTriggerList(l_AreaTriggerList, spell_id);
    if (!l_AreaTriggerList.empty())
    {
        for (auto l_Itr : l_AreaTriggerList)
            l_Itr->RemoveFromWorld();
    }

    // remove dependent skill
    SpellLearnSkillNode const* spellLearnSkill = sSpellMgr->GetSpellLearnSkill(spell_id);
    if (spellLearnSkill)
    {
        uint32 prev_spell = sSpellMgr->GetPrevSpellInChain(spell_id);
        if (!prev_spell)                                    // first rank, remove skill
            SetSkill(spellLearnSkill->skill, 0, 0, 0);
        else
        {
            // search prev. skill setting by spell ranks chain
            SpellLearnSkillNode const* prevSkill = sSpellMgr->GetSpellLearnSkill(prev_spell);
            while (!prevSkill && prev_spell)
            {
                prev_spell = sSpellMgr->GetPrevSpellInChain(prev_spell);
                prevSkill = sSpellMgr->GetSpellLearnSkill(sSpellMgr->GetFirstSpellInChain(prev_spell));
            }

            if (!prevSkill)                                 // not found prev skill setting, remove skill
                SetSkill(spellLearnSkill->skill, 0, 0, 0);
            else                                            // set to prev. skill setting values
            {
                uint32 skill_value = GetPureSkillValue(prevSkill->skill);
                uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);

                if (skill_value > prevSkill->value)
                    skill_value = prevSkill->value;

                uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;

                if (skill_max_value > new_skill_max_value)
                    skill_max_value = new_skill_max_value;

                SetSkill(prevSkill->skill, prevSkill->step, skill_value, skill_max_value);
            }
        }
    }
    else
    {
        // not ranked skills
        SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spell_id);

        for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
        {
            SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
            if (!pSkill)
                continue;

            if ((_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
                pSkill->categoryId != SKILL_CATEGORY_CLASS) ||// not unlearn class skills (spellbook/talent pages)
                // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
                ((pSkill->id == SKILL_LOCKPICKING || pSkill->id == SKILL_RUNEFORGING) && _spell_idx->second->max_value == 0))
            {
                // not reset skills for professions and racial abilities
                if ((pSkill->categoryId == SKILL_CATEGORY_SECONDARY || pSkill->categoryId == SKILL_CATEGORY_PROFESSION) &&
                    (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask != 0))
                    continue;

                SetSkill(pSkill->id, GetSkillStep(pSkill->id), 0, 0);
            }
        }
    }

    // remove dependent spells
    SpellLearnSpellMapBounds spell_bounds = sSpellMgr->GetSpellLearnSpellMapBounds(spell_id);

    for (SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
        removeSpell(itr2->second.spell, disabled);

    // activate lesser rank in spellbook/action bar, and cast it if need
    bool prev_activate = false;

    if (uint32 prev_id = sSpellMgr->GetPrevSpellInChain(spell_id))
    {
        if (cur_active && !spellInfo->IsStackableWithRanks() && spellInfo->IsRanked())
        {
            // need manually update dependence state (learn spell ignore like attempts)
            PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
            if (prev_itr != m_spells.end())
            {
                if (prev_itr->second->dependent != cur_dependent)
                {
                    prev_itr->second->dependent = cur_dependent;
                    if (prev_itr->second->state != PLAYERSPELL_NEW)
                        prev_itr->second->state = PLAYERSPELL_CHANGED;
                }

                // now re-learn if need re-activate
                if (cur_active && !prev_itr->second->active && learn_low_rank)
                {
                    if (addSpell(prev_id, true, false, prev_itr->second->dependent, prev_itr->second->disabled))
                    {
                        // downgrade spell ranks in spellbook and action bar
                        WorldPacket l_Data(SMSG_SUPERCEDED_SPELL);
                        l_Data << uint32(1);
                        l_Data << uint32(1);
                        l_Data << uint32(prev_id);
                        l_Data << uint32(spell_id);
                        GetSession()->SendPacket(&l_Data);
                        prev_activate = true;
                    }
                }
            }
        }
    }

    if (spell_id == 46917 && m_canTitanGrip)
        SetCanTitanGrip(false);
    if (spell_id == 156910 && GetBeaconOfFaithTarget()) ///< Aura should be remove on Ally to not benefit of it on changing spec
    {
        Unit* l_Target = ObjectAccessor::FindUnit(GetBeaconOfFaithTarget());
        if (l_Target != nullptr)
            l_Target->RemoveAura(156910, this->GetGUID());
    }

    if (m_canDualWield)
    {
        SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id);
        if (spellInfo->IsPassive())
        {
            for (int i = 0; i < spellInfo->EffectCount; i++)
                if (spellInfo->Effects[i].Effect == SPELL_EFFECT_DUAL_WIELD)
                {
                    SetCanDualWield(false);
                    break;
                }
        }
    }

    if (sWorld->getBoolConfig(CONFIG_OFFHAND_CHECK_AT_SPELL_UNLEARN))
        AutoUnequipOffhandIfNeed();

    // remove from spell book if not replaced by lesser rank
    if (!prev_activate)
    {
        WorldPacket data(SMSG_UNLEARNED_SPELLS, 4 + 4);
        data << uint32(1);  // Count spells, always one by one
        data << uint32(spell_id);
        data.WriteBit(0);   ///< Unk Wod
        GetSession()->SendPacket(&data);
    }
}

void Player::ReduceSpellCooldown(uint32 p_SpellID, time_t p_ModifyTime)
{
    SpellCooldowns::iterator itr = m_spellCooldowns.find(p_SpellID);
    if (itr == m_spellCooldowns.end())
        return;

    uint64 currTime = 0;
    ACE_OS::gettimeofday().msec(currTime);
    if ((itr->second.end - uint64(p_ModifyTime)) > currTime)
        itr->second.end -= uint64(p_ModifyTime);
    else
        m_spellCooldowns.erase(itr);

    WorldPacket l_Data(SMSG_MODIFY_COOLDOWN, 4 + 18 + 4);
    l_Data << uint32(p_SpellID);
    l_Data << int32(-p_ModifyTime);
    l_Data.WriteBit(false);             ///< IsPetCooldown

    SendDirectMessage(&l_Data);
}

void Player::RemoveSpellCooldown(uint32 p_SpellId, bool p_Update /* = false */)
{
    auto l_Itr = m_spellCooldowns.find(p_SpellId);
    if (l_Itr != m_spellCooldowns.end())
    {
        m_spellCooldowns.erase(l_Itr);

        if (p_Update)
            SendClearCooldown(p_SpellId, this);
    }
}

void Player::RemoveArenaSpellCooldowns(bool p_RemoveActivePetCooldowns)
{
    SpellCooldowns::iterator l_Itr, l_Next;
    for (l_Itr = m_spellCooldowns.begin(); l_Itr != m_spellCooldowns.end(); l_Itr = l_Next)
    {
        l_Next = l_Itr;
        ++l_Next;

        SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_Itr->first);
        uint32 l_Flags = (l_SpellInfo && l_SpellInfo->CategoryEntry) ? l_SpellInfo->CategoryEntry->Flags : 0;

        // check if spellentry is present and if the cooldown is less than 10 min
        if (l_SpellInfo &&
            l_SpellInfo->RecoveryTime < 10 * MINUTE * IN_MILLISECONDS &&
            l_SpellInfo->CategoryRecoveryTime < 10 * MINUTE * IN_MILLISECONDS &&
            (l_Flags & SPELL_CATEGORY_FLAG_COOLDOWN_EXPIRES_AT_DAILY_RESET) == 0)
        {
            // remove & notify
            RemoveSpellCooldown(l_Itr->first, true);
        }
    }

    /// Remove spell charge cooldown that have < 10 min CD
    for (auto l_Itr = m_CategoryCharges.begin(); l_Itr != m_CategoryCharges.end();)
    {
        SpellCategoryEntry const* l_SpellCategory = sSpellCategoryStore.LookupEntry(l_Itr->first);
        if (l_SpellCategory &&
            l_SpellCategory->ChargeRecoveryTime < 10 * MINUTE * IN_MILLISECONDS &&
            (l_SpellCategory->Flags & SPELL_CATEGORY_FLAG_COOLDOWN_EXPIRES_AT_DAILY_RESET) == 0)
        {
            ResetCharges(l_SpellCategory);
            l_Itr = m_CategoryCharges.begin();
        }
        else
            l_Itr++;
    }

    // pet cooldowns
    if (p_RemoveActivePetCooldowns)
    {
        if (Pet* l_Pet = GetPet())
        {
            // notify player
            for (auto l_Itr = l_Pet->m_CreatureSpellCooldowns.begin(); l_Itr != l_Pet->m_CreatureSpellCooldowns.end(); l_Itr++)
                SendClearCooldown(l_Itr->first, l_Pet);

            // actually clear cooldowns
            l_Pet->m_CreatureSpellCooldowns.clear();
        }
    }
}

void Player::RemoveAllSpellCooldown()
{
    if (!m_spellCooldowns.empty())
    {
        WorldPacket l_Data(SMSG_CLEAR_COOLDOWNS, 4 + (m_spellCooldowns.size() * 4));
        l_Data << uint32(GetSpellCooldownMap().size());

        for (SpellCooldowns::const_iterator itr = GetSpellCooldownMap().begin(); itr != GetSpellCooldownMap().end(); ++itr)
            l_Data << uint32(itr->first);             ///< Spell ID

        SendDirectMessage(&l_Data);
        m_spellCooldowns.clear();
    }
}

void Player::_LoadSpellCooldowns(PreparedQueryResult result)
{
    // some cooldowns can be already set at aura loading...

    //QueryResult* result = CharacterDatabase.PQuery("SELECT spell, item, time FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());

    if (result)
    {
        uint64 curTime = 0;
        ACE_OS::gettimeofday().msec(curTime);

        do
        {
            Field* fields = result->Fetch();
            uint32 spell_id = fields[0].GetUInt32();
            uint32 item_id  = fields[1].GetUInt32();
            uint64 db_time = uint64(fields[2].GetUInt32()) * IN_MILLISECONDS;

            if (!sSpellMgr->GetSpellInfo(spell_id))
            {
                sLog->outError(LOG_FILTER_PLAYER_LOADING, "Player %u has unknown spell %u in `character_spell_cooldown`, skipping.", GetGUIDLow(), spell_id);
                continue;
            }

            // skip outdated cooldown
            if (db_time <= curTime)
                continue;

            AddSpellCooldown(spell_id, item_id, (db_time - curTime));

            sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
        }
        while (result->NextRow());
    }
}

void Player::_LoadChargesCooldowns(PreparedQueryResult p_Result)
{
    if (p_Result)
    {
        uint64 l_CurrTime = 0;
        ACE_OS::gettimeofday().msec(l_CurrTime);

        do
        {
            Field* l_Fields = p_Result->Fetch();
            uint32 l_CategoryId = 0;
            ChargeEntry l_Charges;

            l_CategoryId = l_Fields[0].GetUInt32();
            SpellCategoryEntry const* l_Category = sSpellCategoryStore.LookupEntry(l_CategoryId);
            if (l_Category == nullptr)
            {
                sLog->outError(LOG_FILTER_PLAYER_LOADING, "Player %u has unknown charges category %u registered, skipping.", GetGUIDLow(), l_CategoryId);
                continue;
            }

            l_Charges.RechargeStart = Clock::from_time_t(time_t(l_Fields[1].GetUInt32()));
            l_Charges.RechargeEnd = Clock::from_time_t(time_t(l_Fields[2].GetUInt32()));

            m_CategoryCharges[l_CategoryId].push_back(l_Charges);
        }
        while (p_Result->NextRow());
    }
}

void Player::_SaveSpellCooldowns(SQLTransaction& trans)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);

    uint64 curTime = 0;
    ACE_OS::gettimeofday().msec(curTime);
    uint64 infTime = curTime + infinityCooldownDelayCheck;

    bool first_round = true;
    std::ostringstream ss;

    // remove outdated and save active
    for (SpellCooldowns::iterator itr = m_spellCooldowns.begin(); itr != m_spellCooldowns.end();)
    {
        if (itr->second.end <= curTime)
            m_spellCooldowns.erase(itr++);
        else if (itr->second.end <= infTime)                 // not save locked cooldowns, it will be reset or set at reload
        {
            if (first_round)
            {
                ss << "INSERT INTO character_spell_cooldown (guid, spell, item, time) VALUES ";
                first_round = false;
            }
            // next new/changed record prefix
            else
                ss << ',';
            ss << '(' << GetGUIDLow() << ',' << itr->first << ',' << itr->second.itemid << ',' << uint64(itr->second.end / IN_MILLISECONDS) << ')';
            ++itr;
        }
        else
            ++itr;
    }
    // if something changed execute
    if (!first_round)
        trans->Append(ss.str().c_str());
}

void Player::_SaveChargesCooldowns(SQLTransaction& p_Transaction)
{
    PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARGES_COOLDOWN);
    l_Statement->setUInt32(0, GetGUIDLow());
    p_Transaction->Append(l_Statement);

    for (auto const& p : m_CategoryCharges)
    {
        for (ChargeEntry const& l_Charge : p.second)
        {
            PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARGES_COOLDOWN);
            l_Statement->setUInt32(0, GetGUIDLow());
            l_Statement->setUInt32(1, p.first);
            l_Statement->setUInt32(2, uint32(Clock::to_time_t(l_Charge.RechargeStart)));
            l_Statement->setUInt32(3, uint32(Clock::to_time_t(l_Charge.RechargeEnd)));
            p_Transaction->Append(l_Statement);
        }
    }
}

uint32 Player::GetNextResetSpecializationCost() const
{
    // The first time reset costs 1 gold
    if (GetSpecializationResetCost() < 1*GOLD)
        return 1*GOLD;
    // then 5 gold
    else if (GetSpecializationResetCost() < 5*GOLD)
        return 5*GOLD;
    // After that it increases in increments of 5 gold
    else if (GetSpecializationResetCost() < 10*GOLD)
        return 10*GOLD;
    else
    {
        uint64 months = (sWorld->GetGameTime() - GetSpecializationResetTime())/MONTH;
        if (months > 0)
        {
            // This cost will be reduced by a rate of 5 gold per month
            int32 new_cost = int32(GetSpecializationResetCost() - 5*GOLD*months);
            // to a minimum of 10 gold.
            return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
        }
        else
        {
            // After that it increases in increments of 5 gold
            int32 new_cost = GetSpecializationResetCost() + 5*GOLD;
            // until it hits a cap of 50 gold.
            if (new_cost > 50*GOLD)
                new_cost = 50*GOLD;
            return new_cost;
        }
    }
}

uint32 Player::GetNextResetTalentsCost() const
{
    // The first time reset costs 1 gold
    if (GetTalentResetCost() < 1*GOLD)
        return 1*GOLD;
    // then 5 gold
    else if (GetTalentResetCost() < 5*GOLD)
        return 5*GOLD;
    // After that it increases in increments of 5 gold
    else if (GetTalentResetCost() < 10*GOLD)
        return 10*GOLD;
    else
    {
        uint64 months = (sWorld->GetGameTime() - GetTalentResetTime())/MONTH;
        if (months > 0)
        {
            // This cost will be reduced by a rate of 5 gold per month
            int32 new_cost = int32(GetTalentResetCost() - 5*GOLD*months);

            // 50 gold cap
            new_cost = std::min(new_cost, 50 * GOLD);

            // to a minimum of 10 gold.
            return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
        }
        else
        {
            // After that it increases in increments of 5 gold
            int32 new_cost = GetTalentResetCost() + 5*GOLD;
            // until it hits a cap of 50 gold.
            if (new_cost > 50*GOLD)
                new_cost = 50*GOLD;
            return new_cost;
        }
    }
}

bool Player::ResetTalents(bool p_NoCost /*= false*/)
{
    sScriptMgr->OnPlayerTalentsReset(this, p_NoCost);

    /// Not needed after this call
    if (HasAtLoginFlag(AtLoginFlags::AT_LOGIN_RESET_TALENTS))
        RemoveAtLoginFlag(AtLoginFlags::AT_LOGIN_RESET_TALENTS, true);

    uint32 l_TalentPointsForLevel = CalculateTalentsPoints();

    if (!GetUsedTalentCount())
    {
        SetFreeTalentPoints(l_TalentPointsForLevel);
        return false;
    }

    uint32 l_Cost = 0;

    if (!p_NoCost && !sWorld->getBoolConfig(WorldBoolConfigs::CONFIG_NO_RESET_TALENT_COST))
    {
        l_Cost = GetNextResetTalentsCost();

        if (!HasEnoughMoney(uint64(l_Cost)))
        {
            SendBuyError(BuyResult::BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
            return false;
        }
    }

    if (isInCombat())
    {
        SendEquipError(InventoryResult::EQUIP_ERR_NOT_IN_COMBAT, 0, 0, 0);
        return false;
    }

    if (isInStun() || isInRoots())
    {
        SendEquipError(EQUIP_ERR_GENERIC_STUNNED, 0, 0, 0);
        return false;
    }

    if (Pet* l_Pet = GetPet())
        RemovePet(l_Pet, PetSlot::PET_SLOT_ACTUAL_PET_SLOT, true, l_Pet->m_Stampeded);
    else
        RemovePet(NULL, PetSlot::PET_SLOT_ACTUAL_PET_SLOT, true, GetPet() ? GetPet()->m_Stampeded : true);

    for (uint32 l_TalentID = 0; l_TalentID < sTalentStore.GetNumRows(); ++l_TalentID)
    {
        TalentEntry const* l_TalentInfo = sTalentStore.LookupEntry(l_TalentID);
        if (!l_TalentInfo)
            continue;

        /// Unlearn only talents for character class
        /// Some spell learned by one class as normal spells or know at creation but another class learn it as talent,
        /// To prevent unexpected lost normal learned spell skip another class talents
        if (l_TalentInfo->ClassID != getClass())
            continue;

        /// Skip non-existent talent ranks
        if (l_TalentInfo->SpellID == 0)
            continue;

        RemoveTalent(l_TalentInfo);
    }

    SetFreeTalentPoints(l_TalentPointsForLevel);
    SetUsedTalentCount(0);

    SQLTransaction charTrans = CharacterDatabase.BeginTransaction();
    SQLTransaction accountTrans = LoginDatabase.BeginTransaction();
    _SaveTalents(charTrans);
    _SaveSpells(charTrans, accountTrans);
    CharacterDatabase.CommitTransaction(charTrans);
    LoginDatabase.CommitTransaction(accountTrans);

    if (!p_NoCost)
    {
        ModifyMoney(-(int64)l_Cost);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, l_Cost);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);

        SetTalentResetCost(l_Cost);
        SetTalentResetTime(time(NULL));
    }

    return true;
}

void Player::RemoveTalent(TalentEntry const* p_TalentInfos)
{
    SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(p_TalentInfos->SpellID);
    if (!l_SpellInfo)
        return;

    removeSpell(p_TalentInfos->SpellID, true);

    /// Search for spells that the talent teaches and unlearn them
    for (uint8 l_I = 0; l_I < SpellEffIndex::MAX_EFFECTS; ++l_I)
    {
        if (l_SpellInfo->Effects[l_I].TriggerSpell > 0 && l_SpellInfo->Effects[l_I].Effect == SpellEffects::SPELL_EFFECT_LEARN_SPELL)
            removeSpell(l_SpellInfo->Effects[l_I].TriggerSpell, true);
    }

    for (uint8 l_I = 0; l_I < SpellEffIndex::MAX_EFFECTS; ++l_I)
    {
        if (l_SpellInfo->Effects[l_I].ApplyAuraName == AuraType::SPELL_AURA_OVERRIDE_ACTIONBAR_SPELLS ||
            l_SpellInfo->Effects[l_I].ApplyAuraName == AuraType::SPELL_AURA_OVERRIDE_ACTIONBAR_SPELLS_2)
            RemoveAurasDueToSpell(l_SpellInfo->Effects[l_I].BasePoints);
    }

    /// If this talent rank can be found in the PlayerTalentMap, mark the talent as removed so it gets deleted
    PlayerTalentMap::iterator l_PlrTalent = GetTalentMap(GetActiveSpec())->find(p_TalentInfos->SpellID);
    if (l_PlrTalent != GetTalentMap(GetActiveSpec())->end())
        l_PlrTalent->second->state = PlayerSpellState::PLAYERSPELL_REMOVED;

    SetUsedTalentCount(GetUsedTalentCount() - 1);
    SetFreeTalentPoints(GetFreeTalentPoints() + 1);
}

void Player::ResetSpec(bool p_NoCost /* = false */)
{
    uint32 l_Cost = 0;

    if (!sWorld->getBoolConfig(CONFIG_NO_RESET_TALENT_COST) && !p_NoCost)
    {
        l_Cost = GetNextResetSpecializationCost();

        if (!HasEnoughMoney(uint64(l_Cost)))
        {
            SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
            return;
        }
    }

    if (isInCombat())
    {
        SendEquipError(EQUIP_ERR_NOT_IN_COMBAT, 0, 0, 0);
        return;
    }

    if (isInStun() || isInRoots())
    {
        SendEquipError(EQUIP_ERR_GENERIC_STUNNED, 0, 0, 0);
        return;
    }

    if (GetSpecializationId() == SpecIndex::SPEC_NONE)
        return;

    /// Remove specialization Glyphs
    std::vector<uint32> l_Glyphs = GetGlyphMap(GetActiveSpec());
    uint8 l_Slot = 0;
    for (uint32 l_Glyph : l_Glyphs)
    {
        GlyphRequiredSpecEntry const* l_GlyphReq = nullptr;
        for (uint32 l_I = 0; l_I < sGlyphRequiredSpecStore.GetNumRows(); ++l_I)
        {
            if (GlyphRequiredSpecEntry const* l_GlyphRequirements = sGlyphRequiredSpecStore.LookupEntry(l_I))
            {
                if (l_GlyphRequirements->GlyphID == l_Glyph)
                {
                    l_GlyphReq = l_GlyphRequirements;
                    break;
                }
            }
        }

        if (l_GlyphReq == nullptr)
        {
            ++l_Slot;
            continue;
        }

        /// If glyph has a spec requirement, remove it
        if (GlyphPropertiesEntry const* l_GlyphProp = sGlyphPropertiesStore.LookupEntry(l_Glyph))
        {
            RemoveAurasDueToSpell(l_GlyphProp->SpellId);
            SetGlyph(l_Slot, 0);
        }

        ++l_Slot;
    }

    RemoveSpecializationSpells();
    SetSpecializationId(GetActiveSpec(), false);
    InitSpellForLevel();
    UpdateMasteryPercentage();
    SendTalentsInfoData(false);

    ModifyMoney(-(int64)l_Cost);
    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, l_Cost);
    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);

    SetSpecializationResetCost(l_Cost);
    SetSpecializationResetTime(time(nullptr));
}

void Player::ResetAllSpecs()
{
    for (int l_SpecIdx = 0; l_SpecIdx < 2; l_SpecIdx++)
    {
        /// Remove specialization Glyphs
        std::vector<uint32> l_Glyphs = GetGlyphMap(l_SpecIdx);
        uint8 l_Slot = 0;
        for (uint32 l_Glyph : l_Glyphs)
        {
            GlyphRequiredSpecEntry const* l_GlyphReq = nullptr;
            for (uint32 l_I = 0; l_I < sGlyphRequiredSpecStore.GetNumRows(); ++l_I)
            {
                if (GlyphRequiredSpecEntry const* l_GlyphRequirements = sGlyphRequiredSpecStore.LookupEntry(l_I))
                {
                    if (l_GlyphRequirements->GlyphID == l_Glyph)
                    {
                        l_GlyphReq = l_GlyphRequirements;
                        break;
                    }
                }
            }

            if (l_GlyphReq == nullptr)
            {
                ++l_Slot;
                continue;
            }

            /// If glyph has a spec requirement, remove it
            if (GlyphPropertiesEntry const* l_GlyphProp = sGlyphPropertiesStore.LookupEntry(l_Glyph))
            {
                RemoveAurasDueToSpell(l_GlyphProp->SpellId);
                SetGlyph(l_Slot, 0);
            }

            ++l_Slot;
        }
    }

    RemoveSpecializationSpells();
    SetSpecializationId(GetActiveSpec(), false);
    InitSpellForLevel();
    UpdateMasteryPercentage();
    SendTalentsInfoData(false);

    SetSpecializationResetTime(time(nullptr));
}

void Player::SetSpecializationId(uint8 p_Spec, uint32 p_Specialization, bool p_Loading)
{
    /// Hook playerScript OnModifySpec
    sScriptMgr->OnModifySpec(this, p_Specialization);

    /// Remove specialization talents
    for (auto l_Iter : *GetTalentMap(GetActiveSpec()))
    {
        SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_Iter.first);
        if (!l_SpellInfo)
            continue;

        bool l_Remove = false;
        for (uint32 l_TalentID : l_SpellInfo->m_TalentIDs)
        {
            TalentEntry const* l_TalentEntry = sTalentStore.LookupEntry(l_TalentID);
            if (l_TalentEntry && l_TalentEntry->SpecID != p_Specialization)
            {
                l_Remove = true;
                break;
            }
        }

        if (!l_Remove)
            continue;

        removeSpell(l_Iter.first, true);

        for (uint8 i = 0; i < SpellEffIndex::MAX_EFFECTS; ++i)
        {
            if (l_SpellInfo->Effects[i].TriggerSpell > 0 && l_SpellInfo->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL)
                removeSpell(l_SpellInfo->Effects[i].TriggerSpell, true);
        }

        for (uint8 i = 0; i < SpellEffIndex::MAX_EFFECTS; ++i)
        {
            if (l_SpellInfo->Effects[i].ApplyAuraName == SPELL_AURA_OVERRIDE_ACTIONBAR_SPELLS ||
                l_SpellInfo->Effects[i].ApplyAuraName == SPELL_AURA_OVERRIDE_ACTIONBAR_SPELLS_2)
                RemoveAurasDueToSpell(l_SpellInfo->Effects[i].BasePoints);
        }

        l_Iter.second->state = PLAYERSPELL_REMOVED;

        SetUsedTalentCount(GetUsedTalentCount() - 1);
        SetFreeTalentPoints(GetFreeTalentPoints() + 1);
    }

    if (p_Spec == GetActiveSpec())
    {
        float pct = GetHealthPct();
        SetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID, p_Specialization);

        if (!p_Loading)
        {
            for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
            {
                if (Item* item = m_items[i])
                {
                    _ApplyItemMods(item, i, false);
                    RemoveItemsSetItem(this, item->GetTemplate());
                }
            }
        }

        _talentMgr->SpecInfo[p_Spec].SpecializationId = p_Specialization;

        if (!p_Loading)
        {
            for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
            {
                if (Item* item = m_items[i])
                {
                    _ApplyItemMods(item, i, true);
                    AddItemsSetItem(this, item);
                }
            }
        }

        SetHealth(GetMaxHealth() * pct / 100);
        return;
    }
    else
        _talentMgr->SpecInfo[p_Spec].SpecializationId = p_Specialization;

    if (Group* l_Group = GetGroup())
        l_Group->OnChangeMemberSpec(GetGUID(), p_Specialization);

    SaveToDB();
}

uint32 Player::GetRoleForGroup(uint32 specializationId) const
{
    if (!specializationId)
        specializationId = GetSpecializationId();

    return GetRoleBySpecializationId(specializationId);
}

bool Player::IsRangedDamageDealer(bool p_AllowHeal /*= true*/) const
{
    if (GetRoleForGroup() != Roles::ROLE_DAMAGE && !(p_AllowHeal && GetRoleForGroup() == Roles::ROLE_HEALER))
        return false;

    switch (getClass())
    {
        case Classes::CLASS_HUNTER:
        case Classes::CLASS_MAGE:
        case Classes::CLASS_WARLOCK:
            return true;
        default:
            break;
    }

    switch (GetSpecializationId())
    {
        case SpecIndex::SPEC_DRUID_BALANCE:
        case SpecIndex::SPEC_PRIEST_SHADOW:
        case SpecIndex::SPEC_SHAMAN_ELEMENTAL:
            return true;
        case SpecIndex::SPEC_DRUID_RESTORATION:
        case SpecIndex::SPEC_MONK_MISTWEAVER:
        case SpecIndex::SPEC_PALADIN_HOLY:
        case SpecIndex::SPEC_PRIEST_DISCIPLINE:
        case SpecIndex::SPEC_PRIEST_HOLY:
        case SpecIndex::SPEC_SHAMAN_RESTORATION:
            return p_AllowHeal;
        default:
            break;
    }

    return false;
}

bool Player::IsMeleeDamageDealer(bool p_AllowTank /*= false*/) const
{
    if (GetRoleForGroup() != Roles::ROLE_DAMAGE && !(p_AllowTank && GetRoleForGroup() == Roles::ROLE_TANK))
        return false;

    if (getClass() == Classes::CLASS_ROGUE)
        return true;

    switch (GetSpecializationId())
    {
        case SpecIndex::SPEC_DRUID_FERAL:
        case SpecIndex::SPEC_SHAMAN_ENHANCEMENT:
        case SpecIndex::SPEC_MONK_WINDWALKER:
        case SpecIndex::SPEC_WARRIOR_ARMS:
        case SpecIndex::SPEC_WARRIOR_FURY:
        case SpecIndex::SPEC_DK_UNHOLY:
        case SpecIndex::SPEC_DK_FROST:
        case SpecIndex::SPEC_PALADIN_RETRIBUTION:
            return true;
        case SpecIndex::SPEC_DRUID_GUARDIAN:
        case SpecIndex::SPEC_MONK_BREWMASTER:
        case SpecIndex::SPEC_WARRIOR_PROTECTION:
        case SpecIndex::SPEC_DK_BLOOD:
        case SpecIndex::SPEC_PALADIN_PROTECTION:
            return p_AllowTank;
        default:
            break;
    }

    return false;
}

uint32 Player::GetRoleBySpecializationId(uint32 specializationId)
{
   if (specializationId)
        if (ChrSpecializationsEntry const* spec = sChrSpecializationsStore.LookupEntry(specializationId))
        return spec->Role;

    return ROLE_DAMAGE;
}

bool Player::IsActiveSpecTankSpec() const
{
    if (GetSpecializationId() == SPEC_PALADIN_PROTECTION ||
        GetSpecializationId() == SPEC_WARRIOR_PROTECTION ||
        GetSpecializationId() == SPEC_DRUID_GUARDIAN ||
        GetSpecializationId() == SPEC_DK_BLOOD ||
        GetSpecializationId() == SPEC_MONK_BREWMASTER)
        return true;
    return false;
}

Mail* Player::GetMail(uint32 id)
{
    for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
        if ((*itr)->messageID == id)
            return (*itr);

    return NULL;
}

void Player::BuildCreateUpdateBlockForPlayer(UpdateData* data, Player* target) const
{
    if (target == this)
    {
        for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i)
        {
            if (m_items[i] == NULL)
                continue;

            m_items[i]->BuildCreateUpdateBlockForPlayer(data, target);
        }

        for (uint8 i = INVENTORY_SLOT_BAG_START; i < REAGENT_BANK_SLOT_BAG_END; ++i)
        {
            if (m_items[i] == NULL)
                continue;

            m_items[i]->BuildCreateUpdateBlockForPlayer(data, target);
        }
    }

    Unit::BuildCreateUpdateBlockForPlayer(data, target);
}

void Player::DestroyForPlayer(Player* target, bool onDeath) const
{
    Unit::DestroyForPlayer(target, onDeath);

    for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        if (m_items[i] == NULL)
            continue;

        m_items[i]->DestroyForPlayer(target);
    }

    if (target == this)
    {
        for (uint8 i = INVENTORY_SLOT_BAG_START; i < REAGENT_BANK_SLOT_BAG_END; ++i)
        {
            if (m_items[i] == NULL)
                continue;

            m_items[i]->DestroyForPlayer(target);
        }
    }
}

bool Player::HasSpell(uint32 spell) const
{
    PlayerSpellMap::const_iterator itr = m_spells.find(spell);
    return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
        !itr->second->disabled);
}

bool Player::HasTalent(uint32 spell, uint8 spec) const
{
    PlayerTalentMap::const_iterator itr = GetTalentMap(spec)->find(spell);
    return (itr != GetTalentMap(spec)->end() && itr->second->state != PLAYERSPELL_REMOVED);
}

bool Player::HasActiveSpell(uint32 spell) const
{
    PlayerSpellMap::const_iterator itr = m_spells.find(spell);
    return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
        itr->second->active && !itr->second->disabled);
}

TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
{
    if (!trainer_spell)
        return TRAINER_SPELL_RED;

    bool hasSpell = true;
    for (uint8 i = 0; i < SpellEffIndex::MAX_EFFECTS; ++i)
    {
        if (!trainer_spell->learnedSpell[i])
            continue;

        if (!HasSpell(trainer_spell->learnedSpell[i]))
        {
            hasSpell = false;
            break;
        }
    }
    // known spell
    if (hasSpell)
        return TRAINER_SPELL_GRAY;

    // check skill requirement
    if (trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
        return TRAINER_SPELL_RED;

    // check level requirement
    if (getLevel() < trainer_spell->reqLevel)
        return TRAINER_SPELL_RED;

    for (uint8 i = 0; i < SpellEffIndex::MAX_EFFECTS; ++i)
    {
        if (!trainer_spell->learnedSpell[i])
            continue;

        // check race/class requirement
        if (!IsSpellFitByClassAndRace(trainer_spell->learnedSpell[i]))
            return TRAINER_SPELL_RED;

        if (uint32 prevSpell = sSpellMgr->GetPrevSpellInChain(trainer_spell->learnedSpell[i]))
        {
            // check prev.rank requirement
            if (prevSpell && !HasSpell(prevSpell))
                return TRAINER_SPELL_RED;
        }

        SpellsRequiringSpellMapBounds spellsRequired = sSpellMgr->GetSpellsRequiredForSpellBounds(trainer_spell->learnedSpell[i]);
        for (SpellsRequiringSpellMap::const_iterator itr = spellsRequired.first; itr != spellsRequired.second; ++itr)
        {
            // check additional spell requirement
            if (!HasSpell(itr->second))
                return TRAINER_SPELL_RED;
        }
    }

    // check primary prof. limit
    // first rank of primary profession spell when there are no proffesions avalible is disabled
    for (uint8 i = 0; i < SpellEffIndex::MAX_EFFECTS; ++i)
    {
        if (!trainer_spell->learnedSpell[i])
            continue;
        SpellInfo const* learnedSpellInfo = sSpellMgr->GetSpellInfo(trainer_spell->learnedSpell[i]);
        if (learnedSpellInfo && learnedSpellInfo->IsPrimaryProfessionFirstRank() && (GetFreePrimaryProfessionPoints() == 0))
            return TRAINER_SPELL_GREEN_DISABLED;
    }

    return TRAINER_SPELL_GREEN;
}

/**
 * Deletes a character from the database
 *
 * The way, how the characters will be deleted is decided based on the config option.
 *
 * @see Player::DeleteOldCharacters
 *
 * @param playerguid       the low-GUID from the player which should be deleted
 * @param accountId        the account id from the player
 * @param updateRealmChars when this flag is set, the amount of characters on that realm will be updated in the realmlist
 * @param deleteFinally    if this flag is set, the config option will be ignored and the character will be permanently removed from the database
 */
void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars, bool deleteFinally)
{
    // for not existed account avoid update realm
    if (accountId == 0)
        updateRealmChars = false;

    uint32 charDelete_method = sWorld->getIntConfig(CONFIG_CHARDELETE_METHOD);
    uint32 charDelete_minLvl = sWorld->getIntConfig(CONFIG_CHARDELETE_MIN_LEVEL);

    // if we want to finally delete the character or the character does not meet the level requirement,
    // we set it to mode CHAR_DELETE_REMOVE
    if (deleteFinally || Player::GetLevelFromDB(playerguid) < charDelete_minLvl)
        charDelete_method = CHAR_DELETE_REMOVE;

    uint32 guid = GUID_LOPART(playerguid);

    // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
    // bones will be deleted by corpse/bones deleting thread shortly
    sObjectAccessor->ConvertCorpseForPlayer(playerguid);

    if (uint32 guildId = GetGuildIdFromDB(playerguid))
        if (Guild* guild = sGuildMgr->GetGuildById(guildId))
            guild->DeleteMember(guid, false, false, true);

    // the player was uninvited already on logout so just remove from group
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GROUP_MEMBER);
    stmt->setUInt32(0, guid);
    PreparedQueryResult resultGroup = CharacterDatabase.Query(stmt);

    if (resultGroup)
        if (Group* group = sGroupMgr->GetGroupByDbStoreId((*resultGroup)[0].GetUInt32()))
            RemoveFromGroup(group, playerguid);

    // Remove signs from petitions (also remove petitions if owner);
    RemovePetitionsAndSigns(playerguid, 10);

    switch (charDelete_method)
    {
        // Completely remove from the database
        case CHAR_DELETE_REMOVE:
        {
            SQLTransaction trans = CharacterDatabase.BeginTransaction();

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_COD_ITEM_MAIL);
            stmt->setUInt32(0, guid);
            PreparedQueryResult resultMail = CharacterDatabase.Query(stmt);

            if (resultMail)
            {
                do
                {
                    Field* mailFields = resultMail->Fetch();

                    uint32 mail_id       = mailFields[0].GetUInt32();
                    uint8 mailType       = mailFields[1].GetUInt8();
                    uint16 mailTemplateId= mailFields[2].GetUInt16();
                    uint32 sender        = mailFields[3].GetUInt32();
                    std::string subject  = mailFields[4].GetString();
                    std::string body     = mailFields[5].GetString();
                    uint64 money         = mailFields[6].GetUInt64();
                    bool has_items       = mailFields[7].GetBool();

                    // We can return mail now
                    // So firstly delete the old one
                    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_BY_ID);
                    stmt->setUInt32(0, mail_id);
                    trans->Append(stmt);

                    // Mail is not from player
                    if (mailType != MAIL_NORMAL)
                    {
                        if (has_items)
                        {
                            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID);
                            stmt->setUInt32(0, mail_id);
                            trans->Append(stmt);
                        }
                        continue;
                    }

                    MailDraft draft(subject, body);
                    if (mailTemplateId)
                        draft = MailDraft(mailTemplateId, false);    // items are already included

                    if (has_items)
                    {
                        // Data needs to be at first place for Item::LoadFromDB
                        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_MAILITEMS);
                        stmt->setUInt32(0, mail_id);
                        PreparedQueryResult resultItems = CharacterDatabase.Query(stmt);
                        if (resultItems)
                        {
                            do
                            {
                                Field* itemFields = resultItems->Fetch();
                                uint32 item_guidlow = itemFields[15].GetUInt32();
                                uint32 item_template = itemFields[16].GetUInt32();

                                ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_template);
                                if (!itemProto)
                                {
                                    stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
                                    stmt->setUInt32(0, item_guidlow);
                                    trans->Append(stmt);
                                    continue;
                                }

                                Item* pItem = NewItemOrBag(itemProto);
                                if (!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER), itemFields, item_template))
                                {
                                    pItem->FSetState(ITEM_REMOVED);
                                    pItem->SaveToDB(trans);              // it also deletes item object!
                                    continue;
                                }

                                draft.AddItem(pItem);
                            }
                            while (resultItems->NextRow());
                        }
                    }

                    stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID);
                    stmt->setUInt32(0, mail_id);
                    trans->Append(stmt);

                    uint32 pl_account = sObjectMgr->GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));

                    draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender, trans);
                }
                while (resultMail->NextRow());
            }

            // Unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
            // NOW we can finally clear other DB data related to character
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PETS);
            stmt->setUInt32(0, guid);
            PreparedQueryResult resultPets = CharacterDatabase.Query(stmt);

            if (resultPets)
            {
                do
                {
                    uint32 petguidlow = (*resultPets)[0].GetUInt32();
                    Pet::DeleteFromDB(petguidlow);
                }
                while
                    (resultPets->NextRow());
            }

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_ACCOUNT_DATA);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_DECLINED_NAME);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA_EFFECT);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GIFT);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_OBJECTIVE_ALL);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_REPUTATION);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_COOLDOWN);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_GM_TICKETS);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_FRIEND);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            /// Social list is account binded now
            //stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SOCIAL_BY_ACCOUNT_ID);
            //stmt->setUInt32(0, guid);
            //trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEMS);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_BY_OWNER);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_PET_DECLINEDNAME_BY_OWNER);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENTS);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENTS);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_EQUIPMENTSETS);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOG_BY_PLAYER);
            stmt->setUInt32(0, guid);
            stmt->setUInt32(1, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOG_BY_PLAYER);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_BGDATA);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_DAILY);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_TALENT);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILLS);
            stmt->setUInt32(0, guid);
            trans->Append(stmt);

            MS::Garrison::Manager::DeleteFromDB(playerguid, trans);

            MS::Utilities::CallBackPtr l_CharCreateCallback = nullptr;

            if (updateRealmChars)
            {
                l_CharCreateCallback = std::make_shared<MS::Utilities::Callback>([accountId](bool p_Success) -> void ///< p_Success is unused
                {
                    sWorld->UpdateRealmCharCount(accountId);
                });
            }

            CharacterDatabase.CommitTransaction(trans, l_CharCreateCallback);
            break;
        }
        // The character gets unlinked from the account, the name gets freed up and appears as deleted ingame
        case CHAR_DELETE_UNLINK:
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_DELETE_INFO);

            stmt->setUInt32(0, guid);

            CharacterDatabase.Execute(stmt);
            break;
        }
        default:
            sLog->outError(LOG_FILTER_PLAYER, "Player::DeleteFromDB: Unsupported delete method: %u.", charDelete_method);
    }
}

/**
 * Characters which were kept back in the database after being deleted and are now too old (see config option "CharDelete.KeepDays"), will be completely deleted.
 *
 * @see Player::DeleteFromDB
 */
void Player::DeleteOldCharacters()
{
    uint32 keepDays = sWorld->getIntConfig(CONFIG_CHARDELETE_KEEP_DAYS);
    if (!keepDays)
        return;

    Player::DeleteOldCharacters(keepDays);
}

/**
 * Characters which were kept back in the database after being deleted and are older than the specified amount of days, will be completely deleted.
 *
 * @see Player::DeleteFromDB
 *
 * @param keepDays overrite the config option by another amount of days
 */
void Player::DeleteOldCharacters(uint32 keepDays)
{
    sLog->outInfo(LOG_FILTER_PLAYER, "Player::DeleteOldChars: Deleting all characters which have been deleted %u days before...", keepDays);

    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_OLD_CHARS);
    stmt->setUInt32(0, uint32(time(NULL) - time_t(keepDays * DAY)));
    PreparedQueryResult result = CharacterDatabase.Query(stmt);

    if (result)
    {
         sLog->outDebug(LOG_FILTER_PLAYER, "Player::DeleteOldChars: Found " UI64FMTD " character(s) to delete", result->GetRowCount());
         do
         {
            Field* fields = result->Fetch();
            Player::DeleteFromDB(fields[0].GetUInt32(), fields[1].GetUInt32(), true, true);
         }
         while (result->NextRow());
    }
}

/* Preconditions:
  - a resurrectable corpse must not be loaded for the player (only bones)
  - the player must be in world
*/
void Player::BuildPlayerRepop()
{
    WorldPacket l_Data(SMSG_PRE_RESURRECT, 8);
    l_Data.appendPackGUID(GetGUID());
    GetSession()->SendPacket(&l_Data);

    if (getRace() == RACE_NIGHTELF)
        CastSpell(this, 20584, true);
    CastSpell(this, 8326, true);

    if (HasAura(84559) && !InBattleground() && !InArena())
        CastSpell(this, 84559, true); // The Quick and the Dead

    if (HasAura(80354))
        RemoveAurasDueToSpell(80354); // Time Warp

    // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
    // there must be SMSG.STOP_MIRROR_TIMER
    // there we must send 888 opcode

    // the player cannot have a corpse already, only bones which are not returned by GetCorpse
    if (GetCorpse())
    {
        sLog->outError(LOG_FILTER_PLAYER, "BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
        return;
    }

    // create a corpse and place it at the player's location
    CreateCorpse();
    Corpse* corpse = GetCorpse();
    if (!corpse)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
        return;
    }
    GetMap()->AddToMap(corpse);

    /// convert player body to ghost
    SetHealth(1);

    SetWaterWalking(true);

    if (!GetSession()->isLogingOut())
        SetRooted(false);

    /// BG - remove insignia related
    RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);

    /// to prevent cheating
    corpse->ResetGhostTime();

    StopMirrorTimers();                                         ///< disable timers(bars)

    SetFloatValue(UNIT_FIELD_BOUNDING_RADIUS, float(1.0f));     ///< see radius of death player?

    /// set and clear other
    SetByteValue(UNIT_FIELD_ANIM_TIER, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
}

void Player::ResurrectPlayer(float p_RestorePercent, bool p_ApplySickness)
{
    /// remove spirit healer position
    WorldPacket l_Data(SMSG_DEATH_RELEASE_LOC, 4 * 4);
    l_Data << uint32(-1);
    l_Data << float(0);
    l_Data << float(0);
    l_Data << float(0);
    GetSession()->SendPacket(&l_Data);

    // speed change, land walk

    // remove death flag + set aura
    SetByteValue(UNIT_FIELD_ANIM_TIER, 3, 0x00);
    RemoveFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_IS_OUT_OF_BOUNDS);

    if (getRace() == RACE_NIGHTELF)
        RemoveAurasDueToSpell(20584);                       // speed bonuses

    RemoveAurasDueToSpell(8326);                            // SPELL_AURA_GHOST

    if (GetGuild() || HasAura(84559) || HasAura(83950))
        RemoveAurasDueToSpell(84559); // The Quick and the Dead

    if (getClass() == CLASS_MONK && HasAura(131562))
        RemoveAurasDueToSpell(131562);

    if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
        SetFlag(OBJECT_FIELD_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND);

    setDeathState(ALIVE);

    SetWaterWalking(false, true);
    SetRooted(false);

    m_deathTimer = 0;

    // set health/powers (0- will be set in caller)
    if (p_RestorePercent > 0.0f)
    {
        /// Percentage from SPELL_AURA_MOD_RESURRECTED_HEALTH_BY_GUILD_MEMBER
        const AuraEffectList & l_ResurrectedHealthByGuildMember = GetAuraEffectsByType(SPELL_AURA_MOD_RESURRECTED_HEALTH_BY_GUILD_MEMBER);

        for (AuraEffectList::const_iterator l_It = l_ResurrectedHealthByGuildMember.begin(); l_It != l_ResurrectedHealthByGuildMember.end(); ++l_It)
            AddPct(p_RestorePercent, (*l_It)->GetAmount());

        SetHealth(uint32(GetMaxHealth()*p_RestorePercent));
        SetPower(POWER_MANA,   uint32(GetMaxPower(POWER_MANA)   * p_RestorePercent));
        SetPower(POWER_RAGE, 0);
        SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY) * p_RestorePercent));
        SetPower(POWER_FOCUS,  uint32(GetMaxPower(POWER_FOCUS)  * p_RestorePercent));
        SetPower(POWER_ECLIPSE, 0);
        SetPower(POWER_DEMONIC_FURY, 200);
        SetPower(POWER_BURNING_EMBERS, 10);
        SetPower(POWER_SOUL_SHARDS, 100);
        SetPower(POWER_CHI, 0);
        SetPower(POWER_SHADOW_ORB, 0);
    }

    /// Trigger update zone for alive state zone updates
    uint32 l_NewZone, l_NewArea;

    GetZoneAndAreaId(l_NewZone, l_NewArea, true);
    UpdateZone(l_NewZone, l_NewArea);

    sOutdoorPvPMgr->HandlePlayerResurrects(this, l_NewZone);

    if (InBattleground())
    {
        if (Battleground * l_Battleground = GetBattleground())
            l_Battleground->HandlePlayerResurrect(this);
    }

    /// Update visibility
    UpdateObjectVisibility();

    SummonLastSummonedBattlePet();

    /// - Vote bonus
    if (GetSession()->HaveVoteRemainingTime() && !HasAura(VOTE_BUFF))
    {
        Aura* l_VoteAura = AddAura(VOTE_BUFF, this);
        if (l_VoteAura)
            l_VoteAura->SetDuration(GetSession()->GetVoteRemainingTime() + 60 * IN_MILLISECONDS);
    }

    if (!p_ApplySickness)
        return;

    /// Characters from level 1-10 are not affected by resurrection sickness.
    /// Characters from level 11-19 will suffer from one minute of sickness
    /// for each level they are above 10.
    /// Characters level 20 and up suffer from ten minutes of sickness.
    int32 l_StartLevel = sWorld->getIntConfig(CONFIG_DEATH_SICKNESS_LEVEL);

    if (int32(getLevel()) >= l_StartLevel)
    {
        /// Set resurrection sickness
        CastSpell(this, 15007, true);

        /// Not full duration
        if (int32(getLevel()) < l_StartLevel + 9)
        {
            int32 l_Data = (int32(getLevel()) - l_StartLevel + 1)*MINUTE;

            Aura* l_Aura = GetAura(15007, GetGUID());

            if (l_Aura != nullptr)
            {
                l_Aura->SetDuration(l_Data*IN_MILLISECONDS);
            }
        }
    }
}

void Player::KillPlayer()
{
    if (IsFlying() && !GetTransport())
        i_motionMaster.MoveFall();

    SetRooted(true);

    StopMirrorTimers();                                     //disable timers(bars)

    setDeathState(CORPSE);
    //SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP);

    SetUInt32Value(OBJECT_FIELD_DYNAMIC_FLAGS, UNIT_DYNFLAG_NONE);
    ApplyModFlag(PLAYER_FIELD_LIFETIME_MAX_RANK, PLAYER_LOCAL_FLAG_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable() && !HasAuraType(SPELL_AURA_PREVENT_RESURRECTION));

    // 6 minutes until repop at graveyard
    m_deathTimer = 6 * MINUTE * IN_MILLISECONDS;

    UpdateCorpseReclaimDelay();                             // dependent at use SetDeathPvP() call before kill
    SendCorpseReclaimDelay();

    // don't create corpse at this moment, player might be falling

    // update visibility
    UpdateObjectVisibility();

    UnsummonCurrentBattlePetIfAny(true);
}

void Player::CreateCorpse()
{
    // prevent existence 2 corpse for player
    SpawnCorpseBones();

    uint32 _cfb1, _cfb2;

    Corpse* corpse = new Corpse((m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE);
    SetPvPDeath(false);

    if (!corpse->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_CORPSE), this))
    {
        delete corpse;
        return;
    }

    uint8 race          = (uint8)(GetUInt32Value(UNIT_FIELD_SEX));
    uint8 skin          = GetByteValue(PLAYER_FIELD_HAIR_COLOR_ID,  PLAYER_BYTES_OFFSET_SKIN_ID);
    uint8 face          = GetByteValue(PLAYER_FIELD_HAIR_COLOR_ID,  PLAYER_BYTES_OFFSET_FACE_ID);
    uint8 hairstyle     = GetByteValue(PLAYER_FIELD_HAIR_COLOR_ID,  PLAYER_BYTES_OFFSET_HAIR_STYLE_ID);
    uint8 haircolor     = GetByteValue(PLAYER_FIELD_HAIR_COLOR_ID,  PLAYER_BYTES_OFFSET_HAIR_COLOR_ID);
    uint8 facialhair    = GetByteValue(PLAYER_FIELD_REST_STATE,     PLAYER_BYTES_2_OFFSET_FACIAL_STYLE);

    _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
    _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));

    corpse->SetUInt32Value(CORPSE_FIELD_SKIN_ID, _cfb1);
    corpse->SetUInt32Value(CORPSE_FIELD_FACIAL_HAIR_STYLE_ID, _cfb2);

    uint32 flags = CORPSE_FLAG_UNK2;
    if (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
        flags |= CORPSE_FLAG_HIDE_HELM;
    if (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
        flags |= CORPSE_FLAG_HIDE_CLOAK;
    if (InBattleground() && !InArena())
        flags |= CORPSE_FLAG_LOOTABLE;                      // to be able to remove insignia

    corpse->SetUInt32Value(CORPSE_FIELD_FLAGS, flags);
    corpse->SetUInt32Value(CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId());

    uint32 iDisplayID;
    uint32 iIventoryType;
    uint32 _cfi;
    for (uint8 i = 0; i < EQUIPMENT_SLOT_END; i++)
    {
        if (m_items[i])
        {
            iDisplayID = m_items[i]->GetTemplate()->DisplayInfoID;
            iIventoryType = m_items[i]->GetTemplate()->InventoryType;

            _cfi = iDisplayID | (iIventoryType << 24);
            corpse->SetUInt32Value(CORPSE_FIELD_ITEMS + i, _cfi);
        }
    }

    // we do not need to save corpses for BG/arenas
    if (!GetMap()->IsBattlegroundOrArena())
        corpse->SaveToDB();

    // register for player, but not show
    sObjectAccessor->AddCorpse(corpse);
}

void Player::SpawnCorpseBones()
{
    if (sObjectAccessor->ConvertCorpseForPlayer(GetGUID()))
        if (!GetSession()->PlayerLogoutWithSave())          // at logout we will already store the player
            SaveToDB();                                     // prevent loading as ghost without corpse
}

Corpse* Player::GetCorpse() const
{
    return sObjectAccessor->GetCorpseForPlayerGUID(GetGUID());
}

void Player::DurabilityLossAll(double percent, bool inventory)
{
    for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            DurabilityLoss(pItem, percent);

    if (inventory)
    {
        // bags not have durability
        // for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)

        for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
            if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                DurabilityLoss(pItem, percent);

        for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
            if (Bag* pBag = GetBagByPos(i))
                for (uint32 j = 0; j < pBag->GetBagSize(); j++)
                    if (Item* pItem = GetItemByPos(i, j))
                        DurabilityLoss(pItem, percent);
    }
}

void Player::DurabilityLoss(Item* item, double percent)
{
    if (!item)
        return;

    uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAX_DURABILITY);

    if (!pMaxDurability)
        return;

    percent /= GetTotalAuraMultiplier(SPELL_AURA_MOD_DURABILITY_LOSS);

    uint32 pDurabilityLoss = uint32(pMaxDurability*percent);

    if (pDurabilityLoss < 1)
        pDurabilityLoss = 1;

    DurabilityPointsLoss(item, pDurabilityLoss);
}

void Player::DurabilityPointsLossAll(int32 points, bool inventory)
{
    for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            DurabilityPointsLoss(pItem, points);

    if (inventory)
    {
        // bags not have durability
        // for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)

        for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
            if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                DurabilityPointsLoss(pItem, points);

        for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
            if (Bag* pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                for (uint32 j = 0; j < pBag->GetBagSize(); j++)
                    if (Item* pItem = GetItemByPos(i, j))
                        DurabilityPointsLoss(pItem, points);
    }
}

void Player::DurabilityPointsLoss(Item* item, int32 points)
{
    if (HasAuraType(AuraType::SPELL_AURA_DONT_LOOSE_DURABILITY))
        return;

    int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAX_DURABILITY);
    int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
    int32 pNewDurability = pOldDurability - points;

    if (pNewDurability < 0)
        pNewDurability = 0;
    else if (pNewDurability > pMaxDurability)
        pNewDurability = pMaxDurability;

    if (pOldDurability != pNewDurability)
    {
        // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
        if (pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
            _ApplyItemMods(item, item->GetSlot(), false);

        item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);

        // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
        if (pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
            _ApplyItemMods(item, item->GetSlot(), true);

        item->SetState(ITEM_CHANGED, this);
    }
}

void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
{
    if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
        DurabilityPointsLoss(pItem, 1);
}

uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
{
    uint32 TotalCost = 0;
    // equipped, backpack, bags itself
    for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
        TotalCost += DurabilityRepair(((INVENTORY_SLOT_BAG_0 << 8) | i), cost, discountMod, guildBank);

    // bank, buyback and keys not repaired

    // items in inventory bags
    for (uint8 j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
        for (uint8 i = 0; i < MAX_BAG_SIZE; i++)
            TotalCost += DurabilityRepair(((j << 8) | i), cost, discountMod, guildBank);
    return TotalCost;
}

uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
{
    Item* item = GetItemByPos(pos);

    uint32 TotalCost = 0;
    if (!item)
        return TotalCost;

    uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAX_DURABILITY);
    if (!maxDurability)
        return TotalCost;

    uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);

    if (cost)
    {
        uint32 LostDurability = maxDurability - curDurability;
        if (LostDurability>0)
        {
            ItemTemplate const* ditemProto = item->GetTemplate();

            DurabilityCostsEntry const* dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
            if (!dcost)
            {
                sLog->outError(LOG_FILTER_PLAYER_ITEMS, "RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
                return TotalCost;
            }

            uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
            DurabilityQualityEntry const* dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
            if (!dQualitymodEntry)
            {
                sLog->outError(LOG_FILTER_PLAYER_ITEMS, "RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
                return TotalCost;
            }

            uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class, ditemProto->SubClass)];
            uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));

            costs = uint32(costs * discountMod * sWorld->getRate(RATE_REPAIRCOST));

            if (costs == 0)                                   //fix for ITEM_QUALITY_ARTIFACT
                costs = 1;

            if (guildBank)
            {
                if (GetGuildId() == 0)
                {
                    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "You are not member of a guild");
                    return TotalCost;
                }

                Guild* guild = sGuildMgr->GetGuildById(GetGuildId());
                if (!guild)
                    return TotalCost;

                if (!guild->HandleMemberWithdrawMoney(GetSession(), costs, true))
                    return TotalCost;

                guild->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS, TotalCost, 0, 0, nullptr, this);
                TotalCost = costs;
            }
            else if (!HasEnoughMoney(uint64(costs)))
            {
                sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "You do not have enough money");
                return TotalCost;
            }
            else
                ModifyMoney(-int64(costs));
        }
    }

    item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
    item->SetState(ITEM_CHANGED, this);

    // reapply mods for total broken and repaired item if equipped
    if (IsEquipmentPos(pos) && !curDurability)
        _ApplyItemMods(item, pos & 255, true);
    return TotalCost;
}

void Player::RepopAtGraveyard()
{
    // note: this can be called also when the player is alive
    // for example from WorldSession::HandleMovementOpcodes

    AreaTableEntry const* zone = GetAreaEntryByAreaID(GetAreaId());

    if (!zone)
    {
        sLog->outInfo(LOG_FILTER_PLAYER, "Player %u in null area; area id : %u", GetGUIDLow(), GetAreaId());
        return;
    }

    // Such zones are considered unreachable as a ghost and the player must be automatically revived
    if ((!isAlive() && zone && zone->Flags & AREA_FLAG_NEED_FLY) || GetTransport() || GetPositionZ() < GetMap()->GetMinHeight(GetPositionX(), GetPositionY()))
    {
        ResurrectPlayer(0.5f);
        SpawnCorpseBones();
    }

    WorldSafeLocsEntry const* l_ClosestGrave = nullptr;

    // Special handle for battleground maps
    if (Battleground* bg = GetBattleground())
        l_ClosestGrave = bg->GetClosestGraveYard(this);
    else if (IsInGarrison())
    {
        l_ClosestGrave = sObjectMgr->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam());
    }
    // Since Wod, when you die in Dungeon and you release your spirit, you are teleport alived at the entrance of the dungeon.
    else if (GetMap()->IsDungeon())
    {
        AreaTriggerStruct const* l_AreaTrigger = sObjectMgr->GetMapEntranceTrigger(GetMapId());
        if (l_AreaTrigger)
        {
            TeleportToClosestGrave(
                l_AreaTrigger->target_X,
                l_AreaTrigger->target_Y,
                l_AreaTrigger->target_Z,
                GetOrientation(),
                l_AreaTrigger->target_mapId);

            // Since Wod, you are resurected in Dungeon with 100% life.
            ResurrectPlayer(1.0f);
            SpawnCorpseBones();
        }
    }
    else
    {
        if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(GetZoneId()))
            l_ClosestGrave = bf->GetClosestGraveYard(this);
        /// These checks are here to avoid old Outdoor scripts without GetClosestGraveyard function
        else if (sOutdoorPvPMgr->GetOutdoorPvPToZoneId(GetZoneId()) != nullptr &&
            sOutdoorPvPMgr->GetOutdoorPvPToZoneId(GetZoneId())->GetClosestGraveyard(this) != nullptr)
        {
            if (OutdoorPvP* l_OutdoorPvP = sOutdoorPvPMgr->GetOutdoorPvPToZoneId(GetZoneId())) ///< l_OutdoorPvP is unused
                l_ClosestGrave = sOutdoorPvPMgr->GetOutdoorPvPToZoneId(GetZoneId())->GetClosestGraveyard(this);
        }
        else
            l_ClosestGrave = sObjectMgr->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam());
    }

    // stop countdown until repop
    m_deathTimer = 0;

    // if no grave found, stay at the current location
    // and don't show spirit healer location
    if (l_ClosestGrave != nullptr)
        TeleportToClosestGrave(l_ClosestGrave);
    else if (GetPositionZ() < GetMap()->GetMinHeight(GetPositionX(), GetPositionY()))
        TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());

    RemoveFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_IS_OUT_OF_BOUNDS);
}

void Player::TeleportToClosestGrave(float p_X, float p_Y, float p_Z, float p_O, uint32 p_MapId)
{
    TeleportTo(p_MapId, p_X, p_Y, p_Z, p_O);
    UpdateObjectVisibility();

    /// not send if alive, because it used in TeleportTo()
    if (isDead())
    {
        WorldPacket l_Data(SMSG_DEATH_RELEASE_LOC, 4 * 4);  // show spirit healer position on minimap
        l_Data << p_MapId;
        l_Data << p_X;
        l_Data << p_Y;
        l_Data << p_Z;
        GetSession()->SendPacket(&l_Data);
    }
}

void Player::SendCemeteryList(bool p_OnMap)
{
    ByteBuffer l_Buffer(50);
    uint32 l_Counter = 0;

    uint32 l_ZoneID = GetZoneId();
    GraveYardContainer::const_iterator l_GraveLow  = sObjectMgr->GraveYardStore.lower_bound(l_ZoneID);
    GraveYardContainer::const_iterator l_GraveUP   = sObjectMgr->GraveYardStore.upper_bound(l_ZoneID);
    for (GraveYardContainer::const_iterator l_Iter = l_GraveLow; l_Iter != l_GraveUP; ++l_Iter)
    {
        ++l_Counter;
        l_Buffer << uint32(l_Iter->second.safeLocId);
    }

    WorldPacket l_Packet(SMSG_REQUEST_CEMETERY_LIST_RESPONSE, l_Buffer.size() + 4 + 1);
    l_Packet.WriteBit(p_OnMap);
    l_Packet.FlushBits();
    l_Packet << uint32(l_Counter);
    if (l_Counter)
        l_Packet.append(l_Buffer);
    GetSession()->SendPacket(&l_Packet);
}

bool Player::CanJoinConstantChannelInZone(ChatChannelsEntry const* channel, AreaTableEntry const* zone)
{
    if (channel->Flags & CHANNEL_DBC_FLAG_ZONE_DEP && zone->Flags & AREA_FLAG_ARENA_INSTANCE)
        return false;

    if ((channel->Flags & CHANNEL_DBC_FLAG_CITY_ONLY) && (!(zone->Flags & AREA_FLAG_SLAVE_CAPITAL)))
        return false;

    if ((channel->Flags & CHANNEL_DBC_FLAG_GUILD_REQ) && GetGuildId())
        return false;

    return true;
}

void Player::JoinedChannel(Channel* c)
{
    m_channels.push_back(c);
}

void Player::LeftChannel(Channel* c)
{
    m_channels.remove(c);
}

void Player::CleanupChannels()
{
    while (!m_channels.empty())
    {
        Channel* ch = *m_channels.begin();
        m_channels.erase(m_channels.begin());               // remove from player's channel list
        ch->Leave(GetGUID(), false);                        // not send to client, not remove from player's channel list
        if (ChannelMgr* cMgr = channelMgr(GetTeam()))
            cMgr->LeftChannel(ch->GetName());               // deleted channel if empty
    }
    sLog->outDebug(LOG_FILTER_CHATSYS, "Player: channels cleaned up!");
}

void Player::UpdateChatLocaleFiltering()
{
    for (auto l_It = m_channels.begin(); l_It != m_channels.end(); ++l_It)
    {
        Channel* l_Channel = (*l_It);

        if (l_Channel)
            l_Channel->UpdateChatLocaleFiltering(this);
    }
}

void Player::UpdateLocalChannels(uint32 newZone)
{
    if (GetSession()->PlayerLoading() && !IsBeingTeleportedFar())
        return;                                              // The client handles it automatically after loading, but not after teleporting

    AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
    if (!current_zone)
        return;

    ChannelMgr* cMgr = channelMgr(GetTeam());
    if (!cMgr)
        return;

    std::string current_zone_name = current_zone->AreaNameLang;

    for (uint32 i = 0; i < sChatChannelsStore.GetNumRows(); ++i)
    {
        if (ChatChannelsEntry const* channel = sChatChannelsStore.LookupEntry(i))
        {
            Channel* usedChannel = NULL;

			auto itr = std::find_if(m_channels.begin(), m_channels.end(), [&i](Channel const* var) { return var && var->GetChannelId() == i; });
			if (itr != m_channels.end())
				usedChannel = *itr;

            for (JoinedChannelsList::iterator itr = m_channels.begin(); itr != m_channels.end(); ++itr)
            {
                if ((*itr)->GetChannelId() == i)
                {
                    usedChannel = *itr;
                    break;
                }
            }

            Channel* removeChannel = NULL;
            Channel* joinChannel = NULL;
            bool sendRemove = true;

            if (CanJoinConstantChannelInZone(channel, current_zone))
            {
                if (!(channel->Flags & CHANNEL_DBC_FLAG_GLOBAL))
                {
                    if (channel->Flags & CHANNEL_DBC_FLAG_CITY_ONLY && usedChannel)
                        continue;                            // Already on the channel, as city channel names are not changing

                    char new_channel_name_buf[100];
                    char const* currentNameExt;

                    if (channel->Flags & CHANNEL_DBC_FLAG_CITY_ONLY)
                        currentNameExt = sObjectMgr->GetTrinityStringForDBCLocale(LANG_CHANNEL_CITY);
                    else
                        currentNameExt = current_zone_name.c_str();

                    snprintf(new_channel_name_buf, 100, channel->NameLang, currentNameExt);

                    joinChannel = cMgr->GetJoinChannel(new_channel_name_buf, channel->ID);
                    if (usedChannel)
                    {
                        if (joinChannel != usedChannel)
                        {
                            removeChannel = usedChannel;
                            sendRemove = false;              // Do not send leave channel, it already replaced at client
                        }
                        else
                            joinChannel = NULL;
                    }
                }
                else
                    joinChannel = cMgr->GetJoinChannel(channel->NameLang, channel->ID);
            }
            else
                removeChannel = usedChannel;

            if (joinChannel)
                joinChannel->Join(GetGUID(), "");            // Changed Channel: ... or Joined Channel: ...

            if (removeChannel)
            {
                removeChannel->Leave(GetGUID(), sendRemove); // Leave old channel
                std::string name = removeChannel->GetName(); // Store name, (*i)erase in LeftChannel
                LeftChannel(removeChannel);                  // Remove from player's channel list
                cMgr->LeftChannel(name);                     // Delete if empty
            }
        }
    }
}

void Player::LeaveLFGChannel()<--- The function 'LeaveLFGChannel' is never used.
{
    for (JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i)
    {
        if ((*i)->IsLFG())
        {
            (*i)->Leave(GetGUID());
            break;
        }
    }
}

void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
{
    if (modGroup >= BASEMOD_END || modType >= MOD_END) // @todo Comparison of constant 2 with expression of type 'BaseModType' is always false
    {
        sLog->outError(LOG_FILTER_SPELLS_AURAS, "ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
        return;
    }

    switch (modType)
    {
        case FLAT_MOD:
            m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
            break;
        case PCT_MOD:
            ApplyPercentModFloatVar(m_auraBaseMod[modGroup][modType], amount, apply);
            break;
    }

    if (!CanModifyStats())
        return;

    switch (modGroup)
    {
        case CRIT_PERCENTAGE:              UpdateCritPercentage(WeaponAttackType::BaseAttack);                          break;
        case RANGED_CRIT_PERCENTAGE:       UpdateCritPercentage(WeaponAttackType::RangedAttack);                        break;
        case OFFHAND_CRIT_PERCENTAGE:      UpdateCritPercentage(WeaponAttackType::OffAttack);                           break;
        default: break;
    }
}

float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const<--- The function 'GetBaseModValue' is never used.
{
    if (modGroup >= BASEMOD_END || modType >= MOD_END) // @todo Comparison of constant 2 with expression of type 'BaseModType' is always false
    {
        sLog->outError(LOG_FILTER_SPELLS_AURAS, "trial to access non existed BaseModGroup or wrong BaseModType!");
        return 0.0f;
    }

    if (modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
        return 0.0f;

    return m_auraBaseMod[modGroup][modType];
}

float Player::GetTotalBaseModValue(BaseModGroup modGroup) const<--- The function 'GetTotalBaseModValue' is never used.
{
    if (modGroup >= BASEMOD_END)
    {
        sLog->outError(LOG_FILTER_SPELLS_AURAS, "wrong BaseModGroup in GetTotalBaseModValue()!");
        return 0.0f;
    }

    if (m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
        return 0.0f;

    return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
}

float Player::GetRatingMultiplier(CombatRating cr) const
{
    uint8 level = getLevel();

    if (level > GT_MAX_LEVEL)
        level = GT_MAX_LEVEL;

    GtCombatRatingsEntry const* Rating = sGtCombatRatingsStore.LookupEntry(cr * GT_MAX_LEVEL + level - 1);
    
    if (!Rating || !Rating->ratio)
        return 1.0f; ///< By default use minimum coefficient (not must be called)

    return 1.0f / Rating->ratio;
}

float Player::GetRatingBonusValue(CombatRating cr) const
{
    float baseResult = float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATINGS + cr)) * GetRatingMultiplier(cr);

    if (cr != CR_RESILIENCE_PLAYER_DAMAGE_TAKEN)
        return baseResult;

    //return float(1.0f - pow(0.99f, baseResult)) * 100.0f;
    return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATINGS + cr)) / 1070; // temp hack
}

float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
{
    switch (attType)
    {
        case WeaponAttackType::BaseAttack:
            return GetFloatValue(PLAYER_FIELD_MAINHAND_EXPERTISE);
        case WeaponAttackType::OffAttack:
            return GetFloatValue(PLAYER_FIELD_OFFHAND_EXPERTISE);
        case WeaponAttackType::RangedAttack:
            return GetFloatValue(PLAYER_FIELD_RANGED_EXPERTISE);
        default:
            break;
    }
    return 0.0f;
}

float Player::GetPvpHealingBonus() const<--- The function 'GetPvpHealingBonus' is never used.
{
    // Pvp healing cannot work in dungeons
    if (Map* l_Map = GetMap())
        if (l_Map->IsDungeon())
            return 1.0f;

    float l_PvpPower = (1 + GetFloatValue(PLAYER_FIELD_PVP_POWER_HEALING) / 100);

    return l_PvpPower;
}

float Player::OCTRegenMPPerSpirit()
{
    uint8 level = getLevel();
    uint32 pclass = getClass();

    if (level > GT_MAX_LEVEL)
        level = GT_MAX_LEVEL;

    float ratio = 0.0f;
    GtRegenMPPerSptEntry  const* regenBase = sGtRegenMPPerSptStore.LookupEntry((pclass - 1) * GT_MAX_LEVEL + level - 1);
    if (regenBase)
        ratio = regenBase->ratio;

    // Formula get from PaperDollFrame script
    return GetStat(STAT_SPIRIT) * ratio;
}

void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
{
    float oldRating = m_baseRatingValue[cr];
    m_baseRatingValue[cr] += (apply ? value : -value);

    // explicit affected values
    float const multiplier = GetRatingMultiplier(cr);
    float const oldVal = oldRating * multiplier;
    float const newVal = m_baseRatingValue[cr] * multiplier;
    switch (cr)
    {
        case CR_HASTE_MELEE:
        {
            ApplyAttackTimePercentMod(WeaponAttackType::BaseAttack, oldVal, false);
            ApplyAttackTimePercentMod(WeaponAttackType::OffAttack, oldVal, false);
            ApplyAttackTimePercentMod(WeaponAttackType::BaseAttack, newVal, true);
            ApplyAttackTimePercentMod(WeaponAttackType::OffAttack, newVal, true);
            if (getClass() == CLASS_DEATH_KNIGHT)
                UpdateAllRunesRegen();
            break;
        }
        case CR_HASTE_RANGED:
        {
            ApplyAttackTimePercentMod(WeaponAttackType::RangedAttack, oldVal, false);
            ApplyAttackTimePercentMod(WeaponAttackType::RangedAttack, newVal, true);
            break;
        }
        case CR_HASTE_SPELL:
        {
            ApplyCastTimePercentMod(oldVal, false);
            ApplyCastTimePercentMod(newVal, true);
            break;
        }
        default:
            break;
    }

    UpdateRating(cr);
}

void Player::UpdateRating(CombatRating p_CombatRating)
{
    ///< Apply pct modifier from SPELL_AURA_INCREASE_RATING_PCT
    float l_Modifier = 1.0f;
    AuraEffectList const& l_ModRatingPCT = GetAuraEffectsByType(AuraType::SPELL_AURA_INCREASE_RATING_PCT);
    for (AuraEffectList::const_iterator l_Iter = l_ModRatingPCT.begin(); l_Iter != l_ModRatingPCT.end(); ++l_Iter)
    {
        if ((*l_Iter)->GetMiscValue() & (1 << p_CombatRating))
            l_Modifier += float((*l_Iter)->GetAmount()) / 100.0f;
    }

    int32 l_Amount = m_baseRatingValue[p_CombatRating] * l_Modifier;

    // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
    // stat used stored in miscValueB for this aura
    AuraEffectList const& l_ModRatingFromStat = GetAuraEffectsByType(SPELL_AURA_MOD_RATING_FROM_STAT);
    for (AuraEffectList::const_iterator l_Iter = l_ModRatingFromStat.begin(); l_Iter != l_ModRatingFromStat.end(); ++l_Iter)
    {
        if ((*l_Iter)->GetMiscValue() & (1 << p_CombatRating))
            l_Amount += int32(CalculatePct(GetStat(Stats((*l_Iter)->GetMiscValueB())), (*l_Iter)->GetAmount()));
    }

    if (l_Amount < 0)
        l_Amount = 0;

    SetUInt32Value(PLAYER_FIELD_COMBAT_RATINGS + p_CombatRating, uint32(l_Amount));

    if (p_CombatRating >= CR_HASTE_MELEE && p_CombatRating <= CR_HASTE_SPELL)
    {
        float l_HastePct = l_Amount * GetRatingMultiplier(p_CombatRating);

        AuraEffectList const& l_HasteAuras = GetAuraEffectsByType(SPELL_AURA_MOD_CASTING_SPEED_NOT_STACK);
        for (AuraEffectList::const_iterator l_Iter = l_HasteAuras.begin(); l_Iter != l_HasteAuras.end(); ++l_Iter)
        {
            if ((*l_Iter)->GetAmount() > 0)
            {
                l_HastePct *= (1.0f + (*l_Iter)->GetAmount() / 100.0f);
                l_HastePct += (*l_Iter)->GetAmount();
            }
        }

        AuraEffectList const& l_MeleeSlowAuras = GetAuraEffectsByType(SPELL_AURA_MELEE_SLOW);
        for (AuraEffectList::const_iterator l_Iter = l_MeleeSlowAuras.begin(); l_Iter != l_MeleeSlowAuras.end(); ++l_Iter)
        {
            if ((*l_Iter)->GetAmount() > 0)
            {
                l_HastePct *= (1.0f + (*l_Iter)->GetAmount() / 100.0f);
                l_HastePct += (*l_Iter)->GetAmount();
            }
        }

        float l_Haste = 1.0f / (1.0f + l_HastePct / 100.0f);

        ///< Update haste percentage for client
        SetFloatValue(EUnitFields::UNIT_FIELD_MOD_SPELL_HASTE, l_Haste);
        SetFloatValue(EUnitFields::UNIT_FIELD_MOD_HASTE, l_Haste);
        SetFloatValue(EUnitFields::UNIT_FIELD_MOD_RANGED_HASTE, l_Haste);
        SetFloatValue(EUnitFields::UNIT_FIELD_MOD_HASTE_REGEN, l_Haste);
        SetFloatValue(EUnitFields::UNIT_FIELD_MOD_CASTING_SPEED, l_Haste);

        UpdateManaRegen();
        UpdateEnergyRegen();
        UpdateFocusRegen();
        UpdateAllRunesRegen();
    }

    bool l_AffectStats = CanModifyStats();

    switch (p_CombatRating)
    {
        case CR_DODGE:
            UpdateDodgePercentage();
            break;
        case CR_PARRY:
            UpdateParryPercentage();
            break;
        case CR_BLOCK:
            UpdateBlockPercentage();
            break;
        case CR_CRIT_MELEE:
            if (l_AffectStats)
            {
                UpdateCritPercentage(WeaponAttackType::BaseAttack);
                UpdateCritPercentage(WeaponAttackType::OffAttack);
            }
            break;
        case CR_CRIT_RANGED:
            if (l_AffectStats)
                UpdateCritPercentage(WeaponAttackType::RangedAttack);
            break;
        case CR_CRIT_SPELL:
            if (l_AffectStats)
                UpdateAllSpellCritChances();
            break;
        case CR_SPEED:
            UpdateSpeedPercentage();
            break;
        case CR_MASTERY:                                    // Implemented in Player::UpdateMasteryPercentage
            UpdateMasteryPercentage();
            break;
        case CR_MULTISTRIKE:
            UpdateMultistrikePercentage();
            break;
        case CR_LIFESTEAL:
            UpdateLeechPercentage();
            break;
        case CR_VERSATILITY_DAMAGE_DONE:
        case CR_VERSATILITY_DAMAGE_TAKEN:
            UpdateVersatilityPercentage();
            break;
        case CR_AVOIDANCE:
            UpdateAvoidancePercentage();
            break;
        case CR_HASTE_MELEE:                                // Implemented in Player::ApplyRatingMod
        case CR_HASTE_RANGED:
        case CR_HASTE_SPELL:
        case CR_RESILIENCE_PLAYER_DAMAGE_TAKEN:
        case CR_RESILIENCE_CRIT_TAKEN:
        case CR_DEFENSE_SKILL:
        default:
            break;
    }
}

void Player::UpdateAllRatings()
{
    for (int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
        UpdateRating(CombatRating(cr));
}

void Player::SetRegularAttackTime()
{
    for (uint8 i = 0; i < WeaponAttackType::MaxAttack; ++i)
    {
        Item* tmpitem = GetWeaponForAttack(WeaponAttackType(i), true);
        if (tmpitem && !tmpitem->CantBeUse())
        {
            ItemTemplate const* proto = tmpitem->GetTemplate();
            if (proto->Delay)
                SetAttackTime(WeaponAttackType(i), proto->Delay);
        }
        else
            SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);  // If there is no weapon reset attack time to base (might have been changed from forms)
    }
}

//skill+step, checking for max value
bool Player::UpdateSkill(uint32 skill_id, uint32 step)
{
    if (!skill_id)
        return false;

    if (skill_id == SKILL_FIST_WEAPONS)
        skill_id = SKILL_UNARMED;

    SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return false;

    uint16 field = itr->second.pos / 2;
    uint8 offset = itr->second.pos & 1; // itr->second.pos % 2

    uint16 value = GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset);
    uint16 max = GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset);

    if (!max || !value || value >= max)
        return false;

    if (value < max)
    {
        uint16 new_value = value + step;
        if (new_value > max)
            new_value = max;

        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset, new_value);
        if (itr->second.uState != SKILL_NEW)
            itr->second.uState = SKILL_CHANGED;

        UpdateSkillEnchantments(skill_id, value, new_value);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, skill_id);
        return true;
    }

    return false;
}

inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
{
    if (SkillValue >= GrayLevel)
        return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_GREY)*10;
    if (SkillValue >= GreenLevel)
        return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
    if (SkillValue >= YellowLevel)
        return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
    return sWorld->getIntConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
}

bool Player::UpdateCraftSkill(uint32 spellid)
{
    sLog->outDebug(LOG_FILTER_PLAYER_SKILLS, "UpdateCraftSkill spellid %d", spellid);

    SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(spellid);

    for (SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
    {
        if (_spell_idx->second->skillId)
        {
            uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);

            // Alchemy Discoveries here
            SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(spellid);
            if (spellEntry && spellEntry->Mechanic == MECHANIC_DISCOVERY)
            {
                if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
                    learnSpell(discoveredSpell, false);
            }

            uint32 craft_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_CRAFTING);
            int skill_gain_chance = SkillGainChance(SkillValue, _spell_idx->second->max_value, (_spell_idx->second->max_value + _spell_idx->second->min_value)/2, _spell_idx->second->min_value);
            
            // Since 4.0.x, we have bonus skill point reward with somes items ...
            if (_spell_idx->second && _spell_idx->second->skill_gain >craft_skill_gain && skill_gain_chance == sWorld->getIntConfig(CONFIG_SKILL_CHANCE_ORANGE)*10) ///< Comparison of integers of different signs: 'int' and 'unsigned int'
                craft_skill_gain = _spell_idx->second->skill_gain;

            auto skillId = _spell_idx->second->skillId;
            if (UpdateSkillPro(skillId, skill_gain_chance, craft_skill_gain))
            {
                if (SkillLineEntry const* skillEntry = sSkillLineStore.LookupEntry(skillId))
                {
                    if (uint32 parentSkillId = skillEntry->parentSkillLineID)
                        return UpdateSkillPro(parentSkillId, skill_gain_chance, craft_skill_gain);
                }

                return true;
            }

            return false;
        }
    }
    return false;
}

bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator)
{
    sLog->outDebug(LOG_FILTER_PLAYER_SKILLS, "UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);

    uint32 gathering_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_GATHERING);

    // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
    switch (SkillId)
    {
        case SKILL_HERBALISM:
        case SKILL_LOCKPICKING:
        case SKILL_JEWELCRAFTING:
        case SKILL_INSCRIPTION:
            return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator, gathering_skill_gain);
        case SKILL_SKINNING:
            if (sWorld->getIntConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS) == 0)
                return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator, gathering_skill_gain);
            else
                return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld->getIntConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
        case SKILL_MINING:
            if (sWorld->getIntConfig(CONFIG_SKILL_CHANCE_MINING_STEPS) == 0)
                return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator, gathering_skill_gain);
            else
                return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld->getIntConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)), gathering_skill_gain);
    }
    return false;
}

bool Player::UpdateFishingSkill()
{
    sLog->outDebug(LOG_FILTER_PLAYER_SKILLS, "UpdateFishingSkill");

    uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);

    int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);

    uint32 gathering_skill_gain = sWorld->getIntConfig(CONFIG_SKILL_GAIN_GATHERING);

    return UpdateSkillPro(SKILL_FISHING, chance*10, gathering_skill_gain);
}

// levels sync. with spell requirement for skill levels to learn
// bonus abilities in sSkillLineAbilityStore
// Used only to avoid scan DBC at each skill grow
static uint32 g_BonusSkillLevels[] = {75, 150, 225, 300, 375, 450, 525, 600, 700};
static const size_t g_BonusSkillLevelsSize = sizeof(g_BonusSkillLevels) / sizeof(uint32);

bool Player::UpdateSkillPro(uint16 p_SkillId, int32 p_Chance, uint32 p_Step)
{
    sLog->outDebug(LOG_FILTER_PLAYER_SKILLS, "UpdateSkillPro(SkillId %d, Chance %3.1f%%)", p_SkillId, p_Chance / 10.0f);

    if (!p_SkillId)
        return false;

    if (p_Chance <= 0)                                         // speedup in 0 chance case
    {
        sLog->outDebug(LOG_FILTER_PLAYER_SKILLS, "Player::UpdateSkillPro Chance=%3.1f%% missed", p_Chance / 10.0f);
        return false;
    }

    SkillStatusMap::iterator l_It = mSkillStatus.find(p_SkillId);
    if (l_It == mSkillStatus.end() || l_It->second.uState == SKILL_DELETED)
        return false;

    uint16 l_SkillField       = l_It->second.pos / 2;
    uint8  l_SkillFieldOffset = l_It->second.pos & 1; // itr->second.pos % 2

    uint16 l_CurrentSkillValue    = GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + l_SkillField, l_SkillFieldOffset);
    uint16 l_CurrentSkillMaxValue = GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + l_SkillField, l_SkillFieldOffset);

    if (!l_CurrentSkillMaxValue || !l_CurrentSkillValue || l_CurrentSkillValue >= l_CurrentSkillMaxValue)
        return false;

    int32 l_Roll = irand(1, 1000);

    if (l_Roll <= p_Chance)
    {
        uint16 l_NewSkillValue = l_CurrentSkillValue + p_Step;
        if (l_NewSkillValue > l_CurrentSkillMaxValue)
            l_NewSkillValue = l_CurrentSkillMaxValue;

        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + l_SkillField, l_SkillFieldOffset, l_NewSkillValue);

        if (l_It->second.uState != SKILL_NEW)
            l_It->second.uState = SKILL_CHANGED;

        for (size_t l_I = 0; l_I < g_BonusSkillLevelsSize; ++l_I)
        {
            uint32 l_BonusSkillLevel = g_BonusSkillLevels[l_I];
            if (l_CurrentSkillValue < l_BonusSkillLevel && l_NewSkillValue >= l_BonusSkillLevel)
            {
                learnSkillRewardedSpells(p_SkillId, l_NewSkillValue);
                break;
            }
        }

        UpdateSkillEnchantments(p_SkillId, l_CurrentSkillValue, l_NewSkillValue);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, p_SkillId);

        sLog->outDebug(LOG_FILTER_PLAYER_SKILLS, "Player::UpdateSkillPro Chance=%3.1f%% taken", p_Chance / 10.0f);

        return true;
    }

    sLog->outDebug(LOG_FILTER_PLAYER_SKILLS, "Player::UpdateSkillPro Chance=%3.1f%% missed", p_Chance / 10.0f);
    return false;
}

void Player::ModifySkillBonus(uint32 skillid, int32 val, bool talent)
{
    SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return;

    uint16 field = itr->second.pos / 2 + (talent ? PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT : PLAYER_FIELD_SKILL + SKILL_OFFSET_MODIFIER);
    uint8 offset = itr->second.pos & 1; // itr->second.pos % 2

    uint16 bonus = GetUInt16Value(field, offset);

    SetUInt16Value(field, offset, bonus + val);
}

// This functions sets a skill line value (and adds if doesn't exist yet)
// To "remove" a skill line, set it's values to zero
void Player::SetSkill(uint16 id, uint16 step, uint16 newVal, uint16 maxVal)
{
    if (!id)
        return;

    if (IsPrimaryProfessionSkill(id))
    {
        for (uint8 i = 0; i < DEFAULT_MAX_PRIMARY_TRADE_SKILL; ++i)
        {
            if (GetPrimaryProfession(i) == (newVal ? 0 : id))
            {
                SetPrimaryProfession(i, newVal ? id : 0);
                break;
            }
        }
    }

    uint16 currVal;
    SkillStatusMap::iterator itr = mSkillStatus.find(id);

    //has skill
    if (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
    {
        uint16 field = itr->second.pos / 2;
        uint8 offset = itr->second.pos & 1; // itr->second.pos % 2
        currVal = GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset);
        if (newVal)
        {
            // if skill value is going down, update enchantments before setting the new value
            if (newVal < currVal)
                UpdateSkillEnchantments(id, currVal, newVal);

            // update step
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_LINEID + field, offset, id);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_STEP + field, offset, step);
            // update value
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset, newVal);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset, maxVal);

            if (itr->second.uState != SKILL_NEW)
                itr->second.uState = SKILL_CHANGED;

            learnSkillRewardedSpells(id, newVal);
            // if skill value is going up, update enchantments after setting the new value
            if (newVal > currVal)
                UpdateSkillEnchantments(id, currVal, newVal);

            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);
        }
        else                                                //remove
        {
            //remove enchantments needing this skill
            UpdateSkillEnchantments(id, currVal, 0);
            // clear skill fields
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_LINEID + field, offset, id);

            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_STEP + field, offset, 0);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset, 0);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset, 0);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MODIFIER + field, offset, 0);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT + field, offset, 0);

            // mark as deleted or simply remove from map if not saved yet
            if (itr->second.uState != SKILL_NEW)
                itr->second.uState = SKILL_DELETED;
            else
                mSkillStatus.erase(itr);

            // remove all spells that related to this skill
            for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
                if (SkillLineAbilityEntry const* pAbility = sSkillLineAbilityStore.LookupEntry(j))
                    if (pAbility->skillId == id)
                        removeSpell(sSpellMgr->GetFirstSpellInChain(pAbility->spellId));
        }

        if (step == 0 && newVal == 0 && maxVal == 0)
        {
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_LINEID + field, offset, id);
            // update step
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_STEP + field, offset, 0);
            // update value
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset, 0);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset, 0);
        }
    }
    else if (newVal)                                        //add
    {
        currVal = 0;
        for (uint32 i = 0; i < PLAYER_MAX_SKILLS; ++i)
        {
            uint16 field = i / 2;
            uint8 offset = i & 1; // i % 2

            if (!GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_LINEID + field, offset) || GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_LINEID + field, offset) == id)
            {
                SkillLineEntry const* skillEntry = sSkillLineStore.LookupEntry(id);
                if (!skillEntry)
                {
                    sLog->outError(LOG_FILTER_GENERAL, "Skill not found in SkillLineStore: skill #%u", id);
                    return;
                }

                SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_LINEID + field, offset, id);
                SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_STEP + field, offset, step);
                SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset, newVal);
                SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset, maxVal);

                UpdateSkillEnchantments(id, currVal, newVal);
                UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id);
                UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id);

                // insert new entry or update if not deleted old entry yet
                if (itr != mSkillStatus.end())
                {
                    itr->second.pos = i;
                    itr->second.uState = SKILL_CHANGED;
                }
                else
                    mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));

                // apply skill bonuses
                SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MODIFIER + field, offset, 0);
                SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT + field, offset, 0);

                // temporary bonuses
                AuraEffectList const& mModSkill = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL);
                for (AuraEffectList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
                    if ((*j)->GetMiscValue() == int32(id))
                        (*j)->HandleEffect(this, AURA_EFFECT_HANDLE_SKILL, true);

                // permanent bonuses
                AuraEffectList const& mModSkillTalent = GetAuraEffectsByType(SPELL_AURA_MOD_SKILL_TALENT);
                for (AuraEffectList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
                    if ((*j)->GetMiscValue() == int32(id))
                        (*j)->HandleEffect(this, AURA_EFFECT_HANDLE_SKILL, true);

                // Learn all spells for skill
                learnSkillRewardedSpells(id, newVal);
                return;
            }
        }
    }
    // Some spells can be without skills, clean
    else if (itr == mSkillStatus.end() && !newVal)
    {
        for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
            if (SkillLineAbilityEntry const* pAbility = sSkillLineAbilityStore.LookupEntry(j))
                if (pAbility->skillId == id)
                    removeSpell(sSpellMgr->GetFirstSpellInChain(pAbility->spellId), false, false);
    }
}

bool Player::HasSkill(uint32 skill) const
{
    if (!skill)
        return false;

    SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
    return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
}

uint16 Player::GetSkillStep(uint16 skill) const
{
    if (!skill)
        return 0;

    SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return 0;

    return GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_STEP + itr->second.pos / 2, itr->second.pos & 1);
}

uint16 Player::GetSkillValue(uint32 skill) const
{
    if (!skill)
        return 0;

    SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return 0;

    uint16 field = itr->second.pos / 2;
    uint8 offset = itr->second.pos & 1;

    int32 result = int32(GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset));
    result += int32(GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MODIFIER + field, offset));
    result += int32(GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT + field, offset));
    return result < 0 ? 0 : result;
}

uint16 Player::GetMaxSkillValue(uint32 skill) const
{
    if (!skill)
        return 0;

    SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return 0;

    uint16 field = itr->second.pos / 2;
    uint8 offset = itr->second.pos & 1;

    int32 result = int32(GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset));
    result += int32(GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MODIFIER + field, offset));
    result += int32(GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT + field, offset));
    return result < 0 ? 0 : result;
}

uint16 Player::GetPureMaxSkillValue(uint32 skill) const
{
    if (!skill)
        return 0;

    SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return 0;

    uint16 field = itr->second.pos / 2;
    uint8 offset = itr->second.pos & 1;

    return GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset);
}

uint16 Player::GetBaseSkillValue(uint32 skill) const
{
    if (!skill)
        return 0;

    SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return 0;

    uint16 field = itr->second.pos / 2;
    uint8 offset = itr->second.pos & 1;

    int32 result = int32(GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset));
    result += int32(GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT + field, offset));
    return result < 0 ? 0 : result;
}

uint16 Player::GetPureSkillValue(uint32 skill) const
{
    if (!skill)
        return 0;

    SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return 0;

    uint16 field = itr->second.pos / 2;
    uint8 offset = itr->second.pos & 1;

    return GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset);
}

int16 Player::GetSkillPermBonusValue(uint32 skill) const
{
    if (!skill)
        return 0;

    SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return 0;

    uint16 field = itr->second.pos / 2;
    uint8 offset = itr->second.pos & 1;

    return GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT + field, offset);
}

int16 Player::GetSkillTempBonusValue(uint32 skill) const
{
    if (!skill)
        return 0;

    SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
    if (itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
        return 0;

    uint16 field = itr->second.pos / 2;
    uint8 offset = itr->second.pos & 1;

    return GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MODIFIER + field, offset);
}

void Player::SendActionButtons(uint32 p_State) const
{
    WorldPacket l_Data(SMSG_UPDATE_ACTION_BUTTONS, 1 + (MAX_ACTION_BUTTONS * 8));

    if (p_State != 2)
    {
        /// Masks
        for (uint8 l_Button = 0; l_Button < MAX_ACTION_BUTTONS; ++l_Button)
        {
            auto l_Iter = m_actionButtons.find(l_Button);

            if (l_Iter != m_actionButtons.end() && l_Iter->second.uState != ACTIONBUTTON_DELETED)
                l_Data << uint64(l_Iter->second.packedData);
            else
                l_Data << uint64(0);
        }
    }
    else
    {
        for (uint32 l_I = 0; l_I < MAX_ACTION_BUTTONS; l_I++)
            l_Data << uint64(0);
    }

    l_Data << uint8(p_State);

    GetSession()->SendPacket(&l_Data);

    sLog->outInfo(LOG_FILTER_NETWORKIO, "Action Buttons for '%u' spec '%u' Sent", GetGUIDLow(), GetActiveSpec());
}

bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type)
{
    if (button >= MAX_ACTION_BUTTONS)
    {
        sLog->outError(LOG_FILTER_PLAYER_LOADING, "Action %u not added into button %u for player %s: button must be < %u", action, button, GetName(), MAX_ACTION_BUTTONS);
        return false;
    }

    if (action >= MAX_ACTION_BUTTON_ACTION_VALUE)
    {
        sLog->outError(LOG_FILTER_PLAYER_LOADING, "Action %u not added into button %u for player %s: action must be < %u", action, button, GetName(), MAX_ACTION_BUTTON_ACTION_VALUE);
        return false;
    }

    switch (type)
    {
        case ACTION_BUTTON_SPELL:
            if (!sSpellMgr->GetSpellInfo(action))
            {
                sLog->outError(LOG_FILTER_PLAYER_LOADING, "Spell action %u not added into button %u for player %s: spell not exist", action, button, GetName());
                return false;
            }

            if (!HasSpell(action))
            {
                sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::IsActionButtonDataValid Spell action %u not added into button %u for player %s: player don't known this spell", action, button, GetName());
                return false;
            }
            break;
        case ACTION_BUTTON_ITEM:
            if (!sObjectMgr->GetItemTemplate(action))
            {
                sLog->outError(LOG_FILTER_PLAYER_LOADING, "Item action %u not added into button %u for player %s: item not exist", action, button, GetName());
                return false;
            }
            break;
        default:
            break;                                          // other cases not checked at this moment
    }

    return true;
}

ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
{
    if (!IsActionButtonDataValid(button, action, type))
        return NULL;

    // it create new button (NEW state) if need or return existed
    ActionButton& ab = m_actionButtons[button];

    // set data and update to CHANGED if not NEW
    ab.SetActionAndType(action, ActionButtonType(type));

    sLog->outInfo(LOG_FILTER_PLAYER_LOADING, "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, type, button);
    return &ab;
}

void Player::removeActionButton(uint8 button)
{
    ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
    if (buttonItr == m_actionButtons.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
        return;

    if (buttonItr->second.uState == ACTIONBUTTON_NEW)
        m_actionButtons.erase(buttonItr);                   // new and not saved
    else
        buttonItr->second.uState = ACTIONBUTTON_DELETED;    // saved, will deleted at next save

    sLog->outInfo(LOG_FILTER_PLAYER_LOADING, "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow());
}

ActionButton const* Player::GetActionButton(uint8 button)
{
    ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
    if (buttonItr == m_actionButtons.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
        return NULL;

    return &buttonItr->second;
}

int8 Player::GetFreeActionButton()<--- The function 'GetFreeActionButton' is never used.
{
    // 12 is max button of first action bar
    for (uint8 i = 0; i < 12; i++)
        if (!GetActionButton(i))
            return i;

    return -1;
}

bool Player::UpdatePosition(float x, float y, float z, float orientation, bool teleport)
{
    if (!Unit::UpdatePosition(x, y, z, orientation, teleport))
        return false;

    //if (movementInfo.flags & MOVEMENTFLAG_MOVING)
    //    mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE);
    //if (movementInfo.flags & MOVEMENTFLAG_TURNING)
    //    mover->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
    //AURA_INTERRUPT_FLAG_JUMP not sure

    // group update
    if (GetGroup())
        SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);

    // code block for underwater state update
    // Unit::SetPosition() checks for validity and update our coordinates
    // so we re-fetch them instead of using "raw" coordinates from function params
    UpdateUnderwaterState(GetMap(), GetPositionX(), GetPositionY(), GetPositionZ());

    if (GetTrader() && !IsWithinDistInMap(GetTrader(), INTERACTION_DISTANCE))
        GetSession()->SendCancelTrade();

    CheckAreaExploreAndOutdoor();

    return true;
}

void Player::SaveRecallPosition()
{
    m_recallMap = GetMapId();
    m_recallX = GetPositionX();
    m_recallY = GetPositionY();
    m_recallZ = GetPositionZ();
    m_recallO = GetOrientation();
}

void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self, const GuidUnorderedSet& p_IgnoreList)
{
    if (self)
        GetSession()->SendPacket(data);

    JadeCore::MessageDistDeliverer notifier(this, data, dist, false, nullptr, p_IgnoreList);
    VisitNearbyWorldObject(dist, notifier);
}

void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self, bool own_team_only)
{
    if (self)
        GetSession()->SendPacket(data);

    JadeCore::MessageDistDeliverer notifier(this, data, dist, own_team_only);
    VisitNearbyWorldObject(dist, notifier);
}

void Player::SendMessageToSet(WorldPacket* data, Player const* skipped_rcvr, const GuidUnorderedSet& p_IgnoreList)
{
    if (skipped_rcvr != this)
        GetSession()->SendPacket(data);

    // we use World::GetMaxVisibleDistance() because i cannot see why not use a distance
    // update: replaced by GetMap()->GetVisibilityDistance()
    JadeCore::MessageDistDeliverer notifier(this, data, GetVisibilityRange(), false, skipped_rcvr, p_IgnoreList);
    VisitNearbyWorldObject(GetVisibilityRange(), notifier);
}

void Player::SendDirectMessage(WorldPacket* data)
{
    m_session->SendPacket(data);
}

//////////////////////////////////////////////////////////////////////////
/// Cinematic
//////////////////////////////////////////////////////////////////////////
void Player::StopCinematic()
{
    if (m_CinematicSequence && IsInWorld())
    {
        m_CinematicSequence         = NULL;
        m_InCinematic               = false;
        m_CinematicClientStartTime  = 0;

        Unit::UpdatePosition(m_CinematicStartX, m_CinematicStartY, m_CinematicStartZ, m_CinematicStartO, true);

        getHostileRefManager().setOnlineOfflineState(true);

        SetFall(true);

        RemoveAura(60190);
    }
}
void Player::SendCinematicStart(uint32 p_CinematicSequenceId)
{
    WorldPacket l_Data(SMSG_TRIGGER_CINEMATIC, 4);
    l_Data << uint32(p_CinematicSequenceId);
    SendDirectMessage(&l_Data);

    StopCinematic();

    m_CinematicSequence = const_cast<CinematicSequence*>(sCinematicSequenceMgr->GetSequence(p_CinematicSequenceId));

    if (m_CinematicSequence)
    {
        m_CinematicClientStartTime  = (getMSTime() - GetSession()->GetLatency()) + 1500;
        m_InCinematic               = true;

        m_CinematicStartX = m_positionX;
        m_CinematicStartY = m_positionY;
        m_CinematicStartZ = m_positionZ;
        m_CinematicStartO = GetOrientation();

        getHostileRefManager().setOnlineOfflineState(false);

        SetFall(false);

        AddAura(60190, this);
    }
}

void Player::SendMovieStart(uint32 MovieId)
{
    WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
    data << uint32(MovieId);
    SendDirectMessage(&data);

    CurrentPlayedMovie = MovieId;
}

bool Player::CanMountAsPassenger(Player* l_DriverPlayer) const
{
    // Crossfaction mount
    if (GetTeam() != l_DriverPlayer->GetTeam())
    {
        if (!sWorld->getBoolConfig(WorldBoolConfigs::CONFIG_ALLOW_TWO_SIDE_INTERACTION_MOUNT))
            return false;

        if (AreaTableEntry const* l_Zone = GetAreaEntryByAreaID(l_DriverPlayer->GetZoneId()))
        {
            if (l_Zone->Flags & AreaFlags::AREA_FLAG_CAPITAL && !l_Zone->IsSanctuary())
            {
                if (!sWorld->getBoolConfig(WorldBoolConfigs::CONFIG_ALLOW_TWO_SIDE_INTERACTION_MOUNT_CAPITALS))
                    return false;
            }
        }
    }

    return true;
}

void Player::CheckAreaExploreAndOutdoor()
{
    if (!isAlive())
        return;

    if (isInFlight())
        return;

    bool isOutdoor;
    uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(), GetPositionY(), GetPositionZ(), &isOutdoor);

    if (sWorld->getBoolConfig(CONFIG_VMAP_INDOOR_CHECK) && !isOutdoor)
        RemoveAurasWithAttribute(SPELL_ATTR0_OUTDOORS_ONLY);

    if (areaFlag == 0xffff)
        return;
    int offset = areaFlag / 32;

    if (offset >= PLAYER_EXPLORED_ZONES_SIZE)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_FIELD_EXPLORED_ZONES + %u ( %u must be < %u ).", areaFlag, GetPositionX(), GetPositionY(), offset, offset, PLAYER_EXPLORED_ZONES_SIZE);
        return;
    }

    uint32 val = (uint32)(1 << (areaFlag % 32));
    uint32 currFields = GetUInt32Value(PLAYER_FIELD_EXPLORED_ZONES + offset);

    if (!(currFields & val))
    {
        SetUInt32Value(PLAYER_FIELD_EXPLORED_ZONES + offset, (uint32)(currFields | val));

        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);

        AreaTableEntry const* areaEntry = GetAreaEntryByAreaFlagAndMap(areaFlag, GetMapId());
        if (!areaEntry)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player %u discovered unknown area (x: %f y: %f z: %f map: %u", GetGUIDLow(), GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId());
            return;
        }

        if (areaEntry->ExplorationLevel > 0)
        {
            uint32 area = areaEntry->ID;
            if (getLevel() >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
            {
                SendExplorationExperience(area, 0);
            }
            else
            {
                int32 diff = int32(getLevel()) - areaEntry->ExplorationLevel;
                uint32 XP = 0;

                float ExploreXpRate = 1;
                if (GetPersonnalXpRate())
                   ExploreXpRate = GetPersonnalXpRate();
                else
                   ExploreXpRate = sWorld->getRate(RATE_XP_EXPLORE);

                if (diff < -5)
                {
                    XP = uint32(sObjectMgr->GetBaseXP(getLevel()+5) * ExploreXpRate);
                }
                else if (diff > 5)
                {
                    int32 exploration_percent = (100-((diff-5)*5));
                    if (exploration_percent > 100)
                        exploration_percent = 100;
                    else if (exploration_percent < 0)
                        exploration_percent = 0;

                    XP = uint32(sObjectMgr->GetBaseXP(areaEntry->ExplorationLevel) * exploration_percent / 100 * ExploreXpRate);
                }
                else
                {
                    XP = uint32(sObjectMgr->GetBaseXP(areaEntry->ExplorationLevel) * ExploreXpRate);
                }

                if (GetSession()->IsPremium())
                    XP *= sWorld->getRate(RATE_XP_EXPLORE_PREMIUM);

                GiveXP(XP, NULL);
                SendExplorationExperience(area, XP);
            }
            sLog->outInfo(LOG_FILTER_PLAYER, "Player %u discovered a new area: %u", GetGUIDLow(), area);
        }
    }
}

uint32 Player::TeamForRace(uint8 race)
{
    if (ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race))
    {
        switch (rEntry->TeamID)
        {
            case 1: return HORDE;
            case 7: return ALLIANCE;
            case 42: return PANDAREN_NEUTRAL;
        }
    }

    return ALLIANCE;
}

void Player::setFactionForRace(uint8 race)
{
    // temporary hack for rated bg factions
    if (HasAura(81748))
    {
        RemoveAura(81748);
        AddAura(81748, this);
        return;
    }
    else if (HasAura(81744))
    {
        RemoveAura(81744);
        AddAura(81744, this);
        return;
    }

    m_team = TeamForRace(race);

    ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
    setFaction(rEntry ? rEntry->FactionID : 0);
}

ReputationRank Player::GetReputationRank(uint32 faction) const
{
    FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
    return GetReputationMgr().GetRank(factionEntry);
}

//Calculate total reputation percent player gain with quest/creature level
int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest, bool noQuestBonus)
{
    float percent = 100.0f;

    // Get the generic rate first
    if (RepRewardRate const* repData = sObjectMgr->GetRepRewardRate(faction))
    {
        float repRate = for_quest ? repData->quest_rate : repData->creature_rate;
        percent *= repRate;
    }

    float rate = for_quest ? sWorld->getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld->getRate(RATE_REPUTATION_LOWLEVEL_KILL);

    if (rate != 1.0f && creatureOrQuestLevel <= JadeCore::XP::GetGrayLevel(getLevel()))
        percent *= rate;

    float repMod = noQuestBonus ? 0.0f : (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);

    if (!for_quest)
        repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);

    percent += rep > 0 ? repMod : -repMod;

    if (percent <= 0.0f)
        return 0;

    return int32(rep*percent/100);
}

/// Calculates how many reputation points player gains in victim's enemy factions
void Player::RewardReputation(Unit* victim, float rate)
{
    if (!victim || victim->IsPlayer())
        return;

    if (victim->ToCreature()->IsReputationGainDisabled())
        return;

    if (HasAura(186404)) ///< Sign of the Emissary (Weekly event bonus)
    {
        uint32 l_Zone = GetZoneId();
        uint32 l_Team = GetTeam();

        Creature* l_Creature = victim->ToCreature();

        if (l_Creature == nullptr)
            return;

        if (l_Creature->GetMap()->IsMythic() || l_Creature->GetMap()->IsHeroic())
        {
            std::map<int32, int32>    l_ReputationByMap;
            l_ReputationByMap[6988] = 1515;                                 ///< Skyreach / Arakkoa Outcasts
            l_ReputationByMap[6912] = l_Team == ALLIANCE ? 1710 : 1708;     ///< Auchindoun  / Sha'tari Defense (Alliance), Laughing Skull (Horde)
            l_ReputationByMap[7109] = l_Team == ALLIANCE ? 1710 : 1708;     ///< The Everbloom  / Sha'tari Defense (Alliance), Laughing Skull (Horde)
            l_ReputationByMap[6932] = l_Team == ALLIANCE ? 1731 : 1445;     ///< Shadowmoon Burial Grounds  / Council of Exarchs (Alliance), Frostwolf Orcs (Horde)
            l_ReputationByMap[6984] = l_Team == ALLIANCE ? 1731 : 1445;     ///< Grimrail Depot  / Council of Exarchs (Alliance), Frostwolf Orcs (Horde)
            l_ReputationByMap[6951] = l_Team == ALLIANCE ? 1731 : 1445;     ///< Iron Docks  / Council of Exarchs (Alliance), Frostwolf Orcs (Horde)
            l_ReputationByMap[6874] = 1711;                                 ///< Bloodmaul Slag Mines  / Steamwheedle Preservation Society
            l_ReputationByMap[7307] = 1711;                                 ///< Upper Blackrock Spire  / Steamwheedle Preservation Society

            int32 l_FactionID = 0;
            for (auto& l_Reputation : l_ReputationByMap)
            {
                if (l_Zone == l_Reputation.first)
                    l_FactionID = l_Reputation.second;
            }

            if (l_FactionID)
            {
                int16 l_ReputationGain = 20;
                if (l_Creature->IsDungeonBoss())
                    l_ReputationGain = 400;

                FactionEntry const* factionEntry1 = sFactionStore.LookupEntry(l_FactionID);
                uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
                if (factionEntry1)
                    GetReputationMgr().ModifyReputation(factionEntry1, l_ReputationGain);
            }
        }
    }

    ReputationOnKillEntry const* Rep = sObjectMgr->GetReputationOnKilEntry(victim->ToCreature()->GetCreatureTemplate()->Entry);

    if (!Rep)
        return;

    uint32 ChampioningFaction = 0;

    if (GetChampioningFaction())
    {
        // support for: Championing - http://www.wowwiki.com/Championing

        Map const* map = GetMap();
        if (map && map->IsDungeon())
        {
            InstanceTemplate const* instance = sObjectMgr->GetInstanceTemplate(map->GetId());
            if (instance)
            {
                AccessRequirement const* pAccessRequirement = sObjectMgr->GetAccessRequirement(map->GetId(), ((InstanceMap*)map)->GetDifficultyID());
                if (pAccessRequirement)
                {
                    if (!map->IsRaid() && pAccessRequirement->levelMin == 80)
                        ChampioningFaction = GetChampioningFaction();
                }
            }
        }
    }

    // Favored reputation increase START
    uint32 zone = GetZoneId();
    uint32 team = GetTeam();
    float favored_rep_mult = 0;

    if ((HasAura(32096) || HasAura(32098)) && (zone == 3483 || zone == 3562 || zone == 3836 || zone == 3713 || zone == 3714)) favored_rep_mult = 0.25; // Thrallmar's Favor and Honor Hold's Favor
    else if (HasAura(30754) && (Rep->RepFaction1 == 609 || Rep->RepFaction2 == 609) && !ChampioningFaction)                   favored_rep_mult = 0.25; // Cenarion Favor

    if (favored_rep_mult > 0) favored_rep_mult *= 2; // Multiplied by 2 because the reputation is divided by 2 for some reason (See "donerep1 / 2" and "donerep2 / 2") -- if you know why this is done, please update/explain :)
    // Favored reputation increase END

    bool recruitAFriend = GetsRecruitAFriendBonus(false);

    if (Rep->RepFaction1 && (!Rep->TeamDependent || team == ALLIANCE))
    {
        int32 donerep1 = CalculateReputationGain(victim->getLevel(), Rep->RepValue1, ChampioningFaction ? ChampioningFaction : Rep->RepFaction1, false);
        donerep1 = int32(donerep1*(rate + favored_rep_mult));

        if (recruitAFriend)
            donerep1 = int32(donerep1 * (1 + sWorld->getRate(RATE_REPUTATION_RECRUIT_A_FRIEND_BONUS)));

        FactionEntry const* factionEntry1 = sFactionStore.LookupEntry(ChampioningFaction ? ChampioningFaction : Rep->RepFaction1);
        uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
        if (factionEntry1 && current_reputation_rank1 <= Rep->ReputationMaxCap1)
            GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
    }

    if (Rep->RepFaction2 && (!Rep->TeamDependent || team == HORDE))
    {
        int32 donerep2 = CalculateReputationGain(victim->getLevel(), Rep->RepValue2, ChampioningFaction ? ChampioningFaction : Rep->RepFaction2, false);
        donerep2 = int32(donerep2*(rate + favored_rep_mult));

        if (recruitAFriend)
            donerep2 = int32(donerep2 * (1 + sWorld->getRate(RATE_REPUTATION_RECRUIT_A_FRIEND_BONUS)));

        FactionEntry const* factionEntry2 = sFactionStore.LookupEntry(ChampioningFaction ? ChampioningFaction : Rep->RepFaction2);
        uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
        if (factionEntry2 && current_reputation_rank2 <= Rep->ReputationMaxCap2)
            GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
    }
}

//Calculate how many reputation points player gain with the quest
void Player::RewardReputation(Quest const* quest)
{
    bool recruitAFriend = GetsRecruitAFriendBonus(false);

    // quest reputation reward/loss
    for (uint8 i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
    {
        if (!quest->RewardFactionId[i])
            continue;
        if (quest->RewardFactionValueIdOverride[i])
        {
            int32 rep = CalculateReputationGain(GetQuestLevel(quest), quest->RewardFactionValueIdOverride[i]/100, quest->RewardFactionId[i], true, true);

            if (recruitAFriend)
                rep = int32(rep * (1 + sWorld->getRate(RATE_REPUTATION_RECRUIT_A_FRIEND_BONUS)));

            if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(quest->RewardFactionId[i]))
                GetReputationMgr().ModifyReputation(factionEntry, rep);
        }
        else
        {
            uint32 row = ((quest->RewardFactionValueId[i] < 0) ? 1 : 0) + 1;
            uint32 field = abs(quest->RewardFactionValueId[i]);

            if (const QuestFactionRewEntry* pRow = sQuestFactionRewardStore.LookupEntry(row))
            {
                int32 repPoints = pRow->QuestRewFactionValue[field];

                if (!repPoints)
                    continue;

                repPoints = CalculateReputationGain(GetQuestLevel(quest), repPoints, quest->RewardFactionId[i], true);

                if (recruitAFriend)
                    repPoints = int32(repPoints * (1 + sWorld->getRate(RATE_REPUTATION_RECRUIT_A_FRIEND_BONUS)));

                if (const FactionEntry* factionEntry = sFactionStore.LookupEntry(quest->RewardFactionId[i]))
                    GetReputationMgr().ModifyReputation(factionEntry, repPoints);
            }
        }
    }
}

Expansion Player::GetExpByLevel()
{
    uint8 level = getLevel();

    if (level <= 60)
        return EXPANSION_VANILLA;
    else if (level <= 70)
        return EXPANSION_THE_BURNING_CRUSADE;
    else if (level <= 80)
        return  EXPANSION_WRATH_OF_THE_LICH_KING;
    else if (level <= 85)
        return EXPANSION_CATACLYSM;
    else if (level <= 90)
        return EXPANSION_MISTS_OF_PANDARIA;
    else if (level <= 100)
        return EXPANSION_WARLORDS_OF_DRAENOR;
    else
        return EXPANSION_VANILLA;
}

void Player::RewardGuildReputation(Quest const* quest)
{
    if (!GetGuild())
        return;

    uint32 rep = 0;

    switch (GetExpByLevel())
    {
        case EXPANSION_VANILLA:                 rep = 25;
            break;
        case EXPANSION_THE_BURNING_CRUSADE:     rep = 50;
            break;
        case  EXPANSION_WRATH_OF_THE_LICH_KING: rep = 75;
            break;
        case EXPANSION_CATACLYSM:               rep = 100;
            break;
        case EXPANSION_MISTS_OF_PANDARIA:       rep = 150;
            break;
        case EXPANSION_WARLORDS_OF_DRAENOR:     rep = 200;      ///<    Not sure
            break;
        default:                                rep = 0;
            break;
    }

    rep = CalculateReputationGain(GetQuestLevel(quest), rep, REP_GUILD, true);

    if (GetsRecruitAFriendBonus(false))
        rep = int32(rep * (1 + sWorld->getRate(RATE_REPUTATION_RECRUIT_A_FRIEND_BONUS)));

    // Apply reputation multiplier from aura (not stacking-get highest)
    AddPct(rep, GetMaxPositiveAuraModifier(SPELL_AURA_MOD_GUID_REP_GAIN_PCT));

    if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(REP_GUILD))
        GetReputationMgr().ModifyReputation(factionEntry, rep);
}

void Player::UpdateHonorFields()
{
    /// called when rewarding honor and at each save
    time_t now = time_t(time(NULL));
    time_t today = time_t(time(NULL) / DAY) * DAY;

    if (m_lastHonorUpdateTime < today)
    {
        time_t yesterday = today - DAY;

        uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS));

        // update yesterday's contribution
        if (m_lastHonorUpdateTime >= yesterday)
        {
            // this is the first update today, reset today's contribution
            SetUInt32Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, MAKE_PAIR32(0, kills_today));
        }
        else
        {
            // no honor/kills yesterday or today, reset
            SetUInt32Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 0);
        }
    }

    m_lastHonorUpdateTime = now;
}

///Calculate the amount of honor gained based on the victim
///and the size of the group for which the honor is divided
///An exact honor value can also be given (overriding the calcs)
bool Player::RewardHonor(Unit* victim, uint32 groupsize, int32 honor, bool pvptoken, MS::Battlegrounds::RewardCurrencyType::Type p_RewardCurrencyType)
{
    // do not reward honor in arenas, but enable onkill spellproc
    Battleground* l_Bg = GetBattleground();

    if (InArena() && l_Bg != nullptr && !l_Bg->IsSkirmish())
    {
        if (!victim || victim == this || victim->GetTypeId() != TYPEID_PLAYER)
            return false;

        if (GetBGTeam() == victim->ToPlayer()->GetBGTeam())
            return false;

        return true;
    }

    // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
    if (HasAura(SPELL_AURA_PLAYER_INACTIVE))
        return false;

    uint64 victim_guid = 0;
    uint32 victim_rank = 0;

    // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
    UpdateHonorFields();

    // do not reward honor in arenas, but return true to enable onkill spellproc
    if (InBattleground() && l_Bg && ((l_Bg->isArena() && !l_Bg->IsSkirmish()) || l_Bg->IsRatedBG()))
        return true;

    // Promote to float for calculations
    float honor_f = (float)honor;

    if (honor_f <= 0)
    {
        if (!victim || victim == this || victim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
            return false;

        victim_guid = victim->GetGUID();

        if (Player* plrVictim = victim->ToPlayer())
        {
            if (GetTeam() == plrVictim->GetTeam() && !sWorld->IsFFAPvPRealm())
                return false;

            uint8 k_level = getLevel();
            uint8 k_grey = JadeCore::XP::GetGrayLevel(k_level);
            uint8 v_level = victim->getLevel();

            if (v_level <= k_grey)
                return false;

            // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
            //  [0]      Just name
            //  [1..14]  Alliance honor titles and player name
            //  [15..28] Horde honor titles and player name
            //  [29..38] Other title and player name
            //  [39+]    Nothing
            uint32 victim_title = victim->GetUInt32Value(PLAYER_FIELD_PLAYER_TITLE);
                                                        // Get Killer titles, CharTitlesEntry::bit_index
            // Ranks:
            //  title[1..14]  -> rank[5..18]
            //  title[15..28] -> rank[5..18]
            //  title[other]  -> 0
            if (victim_title == 0)
                victim_guid = 0;                        // Don't show HK: <rank> message, only log.
            else if (victim_title < 15)
                victim_rank = victim_title + 4;
            else if (victim_title < 29)
                victim_rank = victim_title - 14 + 4;
            else
                victim_guid = 0;                        // Don't show HK: <rank> message, only log.

            honor_f = ceil(JadeCore::Honor::hk_honor_at_level_f(k_level) * (v_level - k_grey) / (k_level - k_grey));

            // count the number of playerkills in one day
            ApplyModUInt32Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 1, true);
            // and those in a lifetime
            ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, 1, true);
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, victim->getClass());
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, victim->getRace());
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA, GetAreaId());
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL, 1, 0, 0, victim);

            if (Guild* l_Guild = GetGuild())
                l_Guild->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD, 1, 0, 0, nullptr, this);
        }
        else
        {
            if (!victim->ToCreature()->isRacialLeader())
                return false;

            honor_f = 100.0f;                               // ??? need more info
            victim_rank = 19;                               // HK: Leader
        }
    }

    if (victim != NULL)
        if (groupsize > 1)
            honor_f /= groupsize;

    honor_f *= sWorld->getRate(RATE_HONOR);

    if (GetSession()->IsPremium())
        honor_f *= sWorld->getRate(RATE_HONOR_PREMIUM);

    // Back to int now
    honor = std::max(int32(honor_f), 1);
    // honor - for show honor points in log
    // victim_guid - for show victim name in log
    // victim_rank [1..4]  HK: <dishonored rank>
    // victim_rank [5..19] HK: <alliance\horde rank>
    // victim_rank [0, 20+] HK: <>

    // add honor points
    honor = ModifyCurrency(CURRENCY_TYPE_HONOR_POINTS, int32(honor), true, false, false, p_RewardCurrencyType);

    WorldPacket data(SMSG_PVP_CREDIT, 4 + 16 + 2 + 4);
    data << uint32(honor);
    data.appendPackGUID(victim_guid);
    data << uint32(victim_rank);
    GetSession()->SendPacket(&data);

    if (InBattleground() && honor > 0)
    {
        if (Battleground* bg = GetBattleground())
        {
            bg->UpdatePlayerScore(this, NULL, SCORE_BONUS_HONOR, honor, false, p_RewardCurrencyType); //false: prevent looping
        }
    }

    if (sWorld->getBoolConfig(CONFIG_PVP_TOKEN_ENABLE) && pvptoken)
    {
        if (!victim || victim == this || victim ->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
            return true;

        if (victim->IsPlayer())
        {
            // Check if allowed to receive it in current map
            uint8 MapType = sWorld->getIntConfig(CONFIG_PVP_TOKEN_MAP_TYPE);
            if ((MapType == 1 && !InBattleground() && !HasByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP))
                || (MapType == 2 && !HasByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP))
                || (MapType == 3 && !InBattleground()))
                return true;

            uint32 itemId = sWorld->getIntConfig(CONFIG_PVP_TOKEN_ID);
            int32 count = sWorld->getIntConfig(CONFIG_PVP_TOKEN_COUNT);

            if (AddItem(itemId, count))
                ChatHandler(this).PSendSysMessage("You have been awarded a token for slaying another player.");
        }
    }
    return true;
}

void Player::_LoadCurrency(PreparedQueryResult result)
{
    if (!result)
        return;

    do
    {
        Field* fields = result->Fetch();

        uint16 currencyID = fields[0].GetUInt16();

        if (!sCurrencyTypesStore.LookupEntry(currencyID))
            continue;

        PlayerCurrency cur;
        cur.state = PLAYERCURRENCY_UNCHANGED;
        cur.weekCount = fields[1].GetUInt32();
        cur.totalCount = fields[2].GetUInt32();
        cur.seasonTotal = fields[3].GetUInt32();
        cur.flags = fields[4].GetUInt32();
        cur.weekCap = fields[5].GetUInt32();
        cur.needResetCap = fields[6].GetUInt8();

        if (cur.needResetCap)
        {
            cur.weekCap = CalculateCurrencyWeekCap(currencyID);
            cur.needResetCap = false;
            cur.state = PLAYERCURRENCY_CHANGED;
        }

        _currencyStorage.insert(PlayerCurrenciesMap::value_type(currencyID, cur));

    }
    while (result->NextRow());
}

void Player::_SaveCurrency(SQLTransaction& trans)
{
    PreparedStatement* stmt = NULL;
    for (PlayerCurrenciesMap::iterator itr = _currencyStorage.begin(); itr != _currencyStorage.end(); ++itr)
    {
        CurrencyTypesEntry const* entry = sCurrencyTypesStore.LookupEntry(itr->first);
        if (!entry) // should never happen
            continue;

        switch (itr->second.state)
        {
            case PLAYERCURRENCY_NEW:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_PLAYER_CURRENCY);
                stmt->setUInt32(0, GetGUIDLow());
                stmt->setUInt16(1, itr->first);
                stmt->setUInt32(2, itr->second.weekCount);
                stmt->setUInt32(3, itr->second.totalCount);
                stmt->setUInt32(4, itr->second.seasonTotal);
                stmt->setUInt32(5, itr->second.flags);
                stmt->setUInt32(6, itr->second.weekCap);
                stmt->setUInt8(7, itr->second.needResetCap);
                trans->Append(stmt);
                break;
            case PLAYERCURRENCY_CHANGED:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PLAYER_CURRENCY);
                stmt->setUInt32(0, itr->second.weekCount);
                stmt->setUInt32(1, itr->second.totalCount);
                stmt->setUInt32(2, itr->second.seasonTotal);
                stmt->setUInt32(3, itr->second.flags);
                stmt->setUInt32(4, itr->second.weekCap);
                stmt->setUInt8(5, itr->second.needResetCap);
                stmt->setUInt32(6, GetGUIDLow());
                stmt->setUInt16(7, itr->first);
                trans->Append(stmt);
                break;
            default:
                break;
        }

        itr->second.state = PLAYERCURRENCY_UNCHANGED;
    }
}

void Player::SendCurrencies()
{
    WorldPacket l_Data(SMSG_INIT_CURRENCY, 4 + (_currencyStorage.size() * (4 + 4 + 1 + 4 + 4 + 4)));

    l_Data << uint32(_currencyStorage.size());

    for (PlayerCurrenciesMap::const_iterator l_It = _currencyStorage.begin(); l_It != _currencyStorage.end(); ++l_It)
    {
        CurrencyTypesEntry const* l_CurrencyEntry = sCurrencyTypesStore.LookupEntry(l_It->first);

        if (!l_CurrencyEntry) // should never happen
            continue;

        uint32 l_WeekCount      = l_It->second.weekCount;
        uint32 l_WeekCap        = GetCurrencyWeekCap(l_CurrencyEntry->ID);
        uint32 l_SeasonTotal    = l_It->second.seasonTotal;

        l_Data << uint32(l_CurrencyEntry->ID);
        l_Data << uint32(l_It->second.totalCount);

        l_Data.WriteBit(l_WeekCount);
        l_Data.WriteBit(l_WeekCap);
        l_Data.WriteBit(l_SeasonTotal);
        l_Data.WriteBits(l_It->second.flags, 5);
        l_Data.FlushBits();

        if (l_WeekCount)
            l_Data << uint32(l_WeekCount);
        if (l_WeekCap)
            l_Data << uint32(l_WeekCap);
        if (l_SeasonTotal)
            l_Data << uint32(l_SeasonTotal);
    }

    GetSession()->SendPacket(&l_Data);
}

void Player::SendPvpRewards()
{
    WorldPacket l_Packet(SMSG_REQUEST_PVP_REWARDS_RESPONSE, 65);
    l_Packet << (uint32)GetCurrencyOnWeek(CURRENCY_TYPE_CONQUEST_POINTS, false);                         ///< Count of gived all conquest points in week
    l_Packet << (uint32)GetCurrencyWeekCap(CURRENCY_TYPE_CONQUEST_POINTS, false);                        ///< Max Conquest points cap

    l_Packet << (uint32)GetCurrencyOnWeek(CURRENCY_TYPE_CONQUEST_META_ARENA_BG, false);                  ///< Count of gived all conquest points in week
    l_Packet << (uint32)GetCurrencyWeekCap(CURRENCY_TYPE_CONQUEST_META_ARENA_BG, false);                 ///< Max Conquest points cap

    l_Packet << (uint32)GetCurrencyOnWeek(CURRENCY_TYPE_CONQUEST_META_ASHRAN, false);                    ///< Ashran currency week
    l_Packet << (uint32)GetCurrencyWeekCap(CURRENCY_TYPE_CONQUEST_META_ASHRAN, false);                   ///< Ashran currency weekcap

    l_Packet << (uint32)0;                                                                               ///< Count of gived all conquest rewarded in battlegrounds, deprecated
    l_Packet << (uint32)0;                                                                               ///< battleground currency weekcap, deprecated

    l_Packet << (uint32)sWorld->getIntConfig(CONFIG_CURRENCY_CONQUEST_POINTS_RATED_BG_REWARD);           ///< Conquest points from Rated BG win
    l_Packet << (uint32)sWorld->getIntConfig(CONFIG_CURRENCY_CONQUEST_POINTS_ARENA_REWARD);              ///< Conquest points from Arena win

    l_Packet << (uint32)0;  ///< Mask
    l_Packet << (uint32)0;  ///< RewardMoney
    l_Packet << (uint32)0;  ///< RewardXP

    l_Packet << (uint32)0;  ///< ItemCount
    l_Packet << (uint32)0;  ///< CurrencyCount
    l_Packet << (uint32)0;  ///< QuantityCount

    l_Packet.WriteBit(false);   ///< unk

    /// 2x the same reader

    l_Packet << (uint32)0;  ///< Mask
    l_Packet << (uint32)0;  ///< RewardMoney
    l_Packet << (uint32)0;  ///< RewardXP

    l_Packet << (uint32)0;  ///< ItemCount
    l_Packet << (uint32)0;  ///< CurrencyCount
    l_Packet << (uint32)0;  ///< QuantityCount

    l_Packet.WriteBit(false);   ///< unk
    l_Packet.FlushBits();

    GetSession()->SendPacket(&l_Packet);
}

uint32 Player::GetCurrency(uint32 id, bool usePrecision) const
{
    PlayerCurrenciesMap::const_iterator itr = _currencyStorage.find(id);
    if (itr == _currencyStorage.end())
        return 0;

    CurrencyTypesEntry const* currency = sCurrencyTypesStore.LookupEntry(id);
    uint32 precision = (usePrecision && currency->Flags & CURRENCY_FLAG_HIGH_PRECISION) ? CURRENCY_PRECISION : 1;

    return itr->second.totalCount / precision;
}

uint32 Player::GetCurrencyOnWeek(uint32 id, bool usePrecision) const
{
    PlayerCurrenciesMap::const_iterator itr = _currencyStorage.find(id);
    if (itr == _currencyStorage.end())
        return 0;

    CurrencyTypesEntry const* currency = sCurrencyTypesStore.LookupEntry(id);
    uint32 precision = (usePrecision && currency->Flags & CURRENCY_FLAG_HIGH_PRECISION) ? CURRENCY_PRECISION : 1;

    return itr->second.weekCount / precision;
}

uint32 Player::GetCurrencyOnSeason(uint32 id, bool usePrecision) const
{
    PlayerCurrenciesMap::const_iterator itr = _currencyStorage.find(id);
    if (itr == _currencyStorage.end())
        return 0;

    CurrencyTypesEntry const* currency = sCurrencyTypesStore.LookupEntry(id);
    uint32 precision = (usePrecision && currency->Flags & CURRENCY_FLAG_HIGH_PRECISION) ? CURRENCY_PRECISION : 1;

    return itr->second.seasonTotal / precision;
}

bool Player::HasCurrency(uint32 id, uint32 count) const
{
    PlayerCurrenciesMap::const_iterator itr = _currencyStorage.find(id);
    return itr != _currencyStorage.end() && itr->second.totalCount >= count;
}

void Player::ModifyCurrencyFlags(uint32 currencyId, uint8 flags)
{
    if (!currencyId)
        return;

    if (_currencyStorage.find(currencyId) == _currencyStorage.end())
        return;

    _currencyStorage[currencyId].flags = flags;

    if (_currencyStorage[currencyId].state != PLAYERCURRENCY_NEW)
        _currencyStorage[currencyId].state = PLAYERCURRENCY_CHANGED;
}

void Player::ModifyCurrencyAndSendToast(uint32 id, int32 count, bool printLog/* = true*/, bool ignoreMultipliers/* = false*/, bool ignoreLimit /* = false */)
{
    ModifyCurrency(id, count, printLog, ignoreMultipliers, ignoreLimit);

    switch (id)
    {
        case CURRENCY_TYPE_CONQUEST_META_ARENA_BG:
        case CURRENCY_TYPE_CONQUEST_META_RBG:
        case CURRENCY_TYPE_CONQUEST_META_ASHRAN:
            id = CURRENCY_TYPE_CONQUEST_POINTS;
        default:
            break;
    }

    SendDisplayToast(id, count, DISPLAY_TOAST_METHOD_CURRENCY_OR_GOLD, TOAST_TYPE_NEW_CURRENCY, false, false);
}

int32 Player::ModifyCurrency(uint32 p_CurrencyID, int32 p_Count, bool printLog/* = true*/, bool p_IgnoreMultipliers/* = false*/, bool p_IgnoreLimit /* = false */, MS::Battlegrounds::RewardCurrencyType::Type p_RewardCurrencyType /* = None */)
{
    if (!sWorld->getBoolConfig(WorldBoolConfigs::CONFIG_ARENA_SEASON_IN_PROGRESS) && p_Count >= 0 &&
            (  p_CurrencyID == CurrencyTypes::CURRENCY_TYPE_CONQUEST_META_RBG
            || p_CurrencyID == CurrencyTypes::CURRENCY_TYPE_CONQUEST_META_ARENA_BG
            || p_CurrencyID == CurrencyTypes::CURRENCY_TYPE_CONQUEST_POINTS))
        return p_Count;

    CurrencyTypesEntry const* l_CurrencyEntry = sCurrencyTypesStore.LookupEntry(p_CurrencyID);
    if (!l_CurrencyEntry || !p_Count)
        return 0;

    if (!p_IgnoreMultipliers)
    {
        p_Count *= GetTotalAuraMultiplierByMiscValue(SPELL_AURA_MOD_CURRENCY_GAIN, p_CurrencyID);

        if (p_RewardCurrencyType)
        {
            float l_Multiplier = 1.0f;
            Unit::AuraEffectList const& l_ModPvpPercent = GetAuraEffectsByType(SPELL_AURA_MOD_CURRENCY_GAIN_2);
            for (Unit::AuraEffectList::const_iterator i = l_ModPvpPercent.begin(); i != l_ModPvpPercent.end(); ++i)
            {
                if ((*i)->GetMiscValue() == p_CurrencyID && (*i)->GetMiscValueB() == p_RewardCurrencyType)
                    AddPct(l_Multiplier, (*i)->GetAmount());
            }
            p_Count *= l_Multiplier;
        }
    }

    int32 l_Precision = l_CurrencyEntry->Flags & CURRENCY_FLAG_HIGH_PRECISION ? CURRENCY_PRECISION : 1; ///< l_precision is never read 01/18/16
    uint32 l_OldTotalCount          = 0;
    uint32 l_OldWeekCount           = 0;
    uint32 l_OldSeasonTotalCount    = 0;

    PlayerCurrenciesMap::iterator l_CurrencyIT = _currencyStorage.find(p_CurrencyID);
    if (l_CurrencyIT == _currencyStorage.end())
    {
        PlayerCurrency l_NewCurrency;
        l_NewCurrency.state         = PLAYERCURRENCY_NEW;
        l_NewCurrency.totalCount    = 0;
        l_NewCurrency.weekCount     = 0;
        l_NewCurrency.seasonTotal   = 0;
        l_NewCurrency.flags         = 0;
        l_NewCurrency.weekCap       = CalculateCurrencyWeekCap(p_CurrencyID);
        l_NewCurrency.needResetCap  = false;

        _currencyStorage[p_CurrencyID] = l_NewCurrency;
        l_CurrencyIT = _currencyStorage.find(p_CurrencyID);

        l_OldTotalCount       = 0;
        l_OldWeekCount        = 0;
        l_OldSeasonTotalCount = 0;
    }
    else
    {
        l_OldTotalCount       = l_CurrencyIT->second.totalCount;
        l_OldWeekCount        = l_CurrencyIT->second.weekCount;
        l_OldSeasonTotalCount = l_CurrencyIT->second.seasonTotal;
    }

    /// count can't be more then weekCap.
    uint32 l_WeekCap = GetCurrencyWeekCap(l_CurrencyEntry->ID);
    if (!p_IgnoreLimit && l_WeekCap && p_Count > int32(l_WeekCap))
        p_Count = l_WeekCap;

    int32 l_NewTotalCount = int32(l_OldTotalCount) + p_Count;
    if (l_NewTotalCount < 0)
        l_NewTotalCount = 0;

    int32 l_NewWeekCount = !p_IgnoreLimit ? (int32(l_OldWeekCount) + (p_Count > 0 ? p_Count : 0)) : int32(l_OldWeekCount);
    if (l_NewWeekCount < 0)
        l_NewWeekCount = 0;

    int32 l_NewSeasonTotalCount = !p_IgnoreLimit ? (int32(l_OldSeasonTotalCount) + (p_Count > 0 ? p_Count : 0)) : int32(l_OldSeasonTotalCount);

    if (!p_IgnoreLimit)
    {
        /// if we get more then weekCap just set to limit
        if (l_WeekCap && int32(l_WeekCap) < l_NewWeekCount)
        {
            l_NewWeekCount = int32(l_WeekCap);
            /// weekCap - oldWeekCount alwayt >= 0 as we set limit before!
            l_NewTotalCount = l_OldTotalCount + (l_WeekCap - l_OldWeekCount);
        }

        /// if we get more then totalCap set to maximum;
        if (l_CurrencyEntry->TotalCap && int32(l_CurrencyEntry->TotalCap) < l_NewTotalCount)
        {
            l_NewTotalCount = int32(l_CurrencyEntry->TotalCap);
            l_NewWeekCount = l_WeekCap;
        }
    }

    if (l_NewWeekCount < 0)
        l_NewWeekCount = 0;
    if (l_NewTotalCount < 0)
        l_NewTotalCount = 0;

    if (p_CurrencyID == CURRENCY_TYPE_HONOR_POINTS || p_CurrencyID == CURRENCY_TYPE_JUSTICE_POINTS)
    {
        l_NewWeekCount = l_NewTotalCount;
        l_WeekCap = 0;
    }

    if (uint32(l_NewTotalCount) != l_OldTotalCount)
    {
        if (l_CurrencyIT->second.state != PLAYERCURRENCY_NEW)
            l_CurrencyIT->second.state = PLAYERCURRENCY_CHANGED;

        l_CurrencyIT->second.totalCount = l_NewTotalCount;
        l_CurrencyIT->second.weekCount = l_NewWeekCount;
        l_CurrencyIT->second.seasonTotal = l_NewSeasonTotalCount;

        // probably excessive checks
        if (IsInWorld() && !GetSession()->PlayerLoading())
        {
            if (p_Count > 0 && !p_IgnoreLimit)
                UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_CURRENCY, p_CurrencyID, p_Count);

            if (l_CurrencyEntry->Category == CURRENCY_CATEGORY_META_CONQUEST)
            {
                // count was changed to week limit, now we can modify original points.
                ModifyCurrency(CURRENCY_TYPE_CONQUEST_POINTS, p_Count, printLog);
                return p_Count;
            }

            if (p_CurrencyID == CURRENCY_TYPE_CONQUEST_POINTS)
                SendPvpRewards();

            /// Update archaeology projects
            if (l_CurrencyEntry->Flags & CURRENCY_FLAG_ARCHAEOLOGY_FRAGMENT && GetSkillValue(SKILL_ARCHAEOLOGY))
                m_archaeologyMgr.GenerateResearchProjects();

             // on new case just set init.
            if (l_OldTotalCount == 0 && l_CurrencyIT->second.state == PLAYERCURRENCY_NEW)
            {
                l_CurrencyIT->second.weekCap = CalculateCurrencyWeekCap(p_CurrencyID);
                SendCurrencies();
                return p_Count;
            }

            QuestObjectiveSatisfy(p_CurrencyID, p_Count, QUEST_OBJECTIVE_TYPE_CURRENCY);

            WorldPacket l_Packet(SMSG_UPDATE_CURRENCY);

            l_Packet << uint32(p_CurrencyID);
            l_Packet << uint32(l_NewTotalCount);
            l_Packet << uint32(l_CurrencyIT->second.flags);

            l_Packet.WriteBit(l_WeekCap != 0);
            l_Packet.WriteBit(l_CurrencyIT->second.seasonTotal);
            l_Packet.WriteBit(0);                         // SuppressChatLog
            l_Packet.FlushBits();

            if (l_WeekCap)
                l_Packet << uint32(l_NewWeekCount);

            if (l_CurrencyIT->second.seasonTotal)
                l_Packet << uint32(l_CurrencyIT->second.seasonTotal);

            GetSession()->SendPacket(&l_Packet);
        }
    }
    return p_Count;
}

void Player::SetCurrency(uint32 id, uint32 count, bool printLog /*= true*/)
{
    ModifyCurrency(id, int32(count) - GetCurrency(id, true), printLog);
}

uint32 Player::GetCurrencyWeekCap(uint32 id, bool usePrecision)
{
    CurrencyTypesEntry const* entry = sCurrencyTypesStore.LookupEntry(id);
    if (!entry)
        return 0;

    uint32 precision = (usePrecision && entry->Flags & CURRENCY_FLAG_HIGH_PRECISION) ? CURRENCY_PRECISION : 1;

    PlayerCurrenciesMap::const_iterator itr = _currencyStorage.find(id);
    if (itr == _currencyStorage.end())
    {
        PlayerCurrency cur;
        cur.state = PLAYERCURRENCY_NEW;
        cur.totalCount = 0;
        cur.weekCount = 0;
        cur.seasonTotal = 0;
        cur.flags = 0;
        cur.weekCap = CalculateCurrencyWeekCap(id);
        cur.needResetCap = false;
        _currencyStorage[id] = cur;
        itr = _currencyStorage.find(id);
    }

    return itr->second.weekCap / precision;
}

void Player::ResetCurrencyWeekCap()
{
    FinishWeek();                              // set played this week etc values to 0 in memory, too

    for (PlayerCurrenciesMap::iterator itr = _currencyStorage.begin(); itr != _currencyStorage.end(); ++itr)
    {
        itr->second.weekCount = 0;
        itr->second.state = PLAYERCURRENCY_CHANGED;
        itr->second.weekCap = CalculateCurrencyWeekCap(itr->first);
    }

    WorldPacket data(SMSG_WEEKLY_RESET_CURRENCY, 0);
    SendDirectMessage(&data);
}

uint32 Player::CalculateCurrencyWeekCap(uint32 id)
{
    CurrencyTypesEntry const* entry = sCurrencyTypesStore.LookupEntry(id);

    if (!entry)
        return 0;

    uint32 cap = entry->WeekCap;

    switch (entry->ID)
    {
        case CurrencyTypes::CURRENCY_TYPE_CONQUEST_META_ARENA_BG:
        {
            uint32 l_MaxRating = 0;
            for (int l_Slot = 0; l_Slot < MAX_ARENA_SLOT; ++ l_Slot)
                if (GetPrevWeekGames(l_Slot))
                    l_MaxRating = std::max(l_MaxRating, GetArenaPersonalRating(l_Slot));

            cap = Arena::GetConquestCapFromRating(l_MaxRating) * CURRENCY_PRECISION;
            break;
        }
        case CurrencyTypes::CURRENCY_TYPE_CONQUEST_META_ASHRAN:
            cap = sWorld->getIntConfig(CONFIG_CURRENCY_ASHRAN_CONQUEST_POINTS_WEEK_CAP);
            break;
        case CurrencyTypes::CURRENCY_TYPE_CONQUEST_POINTS:
        {
            uint32 l_MaxRating = 0;

            for (int l_Slot = 0; l_Slot < MAX_ARENA_SLOT; ++ l_Slot)
                if (GetPrevWeekGames(l_Slot))
                    l_MaxRating = std::max(l_MaxRating, GetArenaPersonalRating(l_Slot));

            cap = Arena::GetConquestCapFromRating(l_MaxRating) * CURRENCY_PRECISION + sWorld->getIntConfig(CONFIG_CURRENCY_ASHRAN_CONQUEST_POINTS_WEEK_CAP);
            break;
        }
    }

    return cap;
}

void Player::SetInGuild(uint32 guildId)
{
    if (guildId)
        SetGuidValue(OBJECT_FIELD_DATA, MAKE_NEW_GUID(guildId, 0, HIGHGUID_GUILD));
    else
        SetGuidValue(OBJECT_FIELD_DATA, 0);

    ApplyModFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GUILD_LEVEL_ENABLED, guildId != 0 && sWorld->getBoolConfig(CONFIG_GUILD_LEVELING_ENABLED));
    SetUInt16Value(OBJECT_FIELD_TYPE, 1, guildId != 0);
}

uint32 Player::GetGuildIdFromDB(uint64 guid)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER);
    stmt->setUInt32(0, GUID_LOPART(guid));
    if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
        return result->Fetch()[0].GetUInt32();

    return 0;
}

uint8 Player::GetRankFromDB(uint64 guid)<--- The function 'GetRankFromDB' is never used.
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GUILD_MEMBER);
    stmt->setUInt32(0, GUID_LOPART(guid));
    if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
        return result->Fetch()[1].GetUInt8();

    return 0;
}

uint32 Player::GetZoneIdFromDB(uint64 guid)
{
    uint32 guidLow = GUID_LOPART(guid);
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_ZONE);
    stmt->setUInt32(0, guidLow);
    PreparedQueryResult result = CharacterDatabase.Query(stmt);

    if (!result)
        return 0;
    Field* fields = result->Fetch();
    uint32 zone = fields[0].GetUInt16();

    if (!zone)
    {
        // stored zone is zero, use generic and slow zone detection
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_POSITION_XYZ);
        stmt->setUInt32(0, guidLow);
        PreparedQueryResult result = CharacterDatabase.Query(stmt);

        if (!result)
            return 0;
        fields = result->Fetch();
        uint32 map = fields[0].GetUInt16();
        float posx = fields[1].GetFloat();
        float posy = fields[2].GetFloat();
        float posz = fields[3].GetFloat();

        if (!sMapStore.LookupEntry(map))
            return 0;

        zone = sMapMgr->GetZoneId(map, posx, posy, posz);

        if (zone > 0)
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ZONE);

            stmt->setUInt16(0, uint16(zone));
            stmt->setUInt32(1, guidLow);

            CharacterDatabase.Execute(stmt);
        }
    }

    return zone;
}

uint32 Player::GetLevelFromDB(uint64 guid)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_LEVEL);
    stmt->setUInt32(0, GUID_LOPART(guid));
    PreparedQueryResult result = CharacterDatabase.Query(stmt);

    if (!result)
        return 0;

    Field* fields = result->Fetch();
    uint8 level = fields[0].GetUInt8();

    return level;
}

void Player::UpdateArea(uint32 newArea)
{
    uint32 l_OldArea = m_areaUpdateId;

    // FFA_PVP flags are area and not zone id dependent
    // so apply them accordingly
    m_areaUpdateId    = newArea;

    phaseMgr.AddUpdateFlag(PHASE_UPDATE_FLAG_AREA_UPDATE);

    AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
    pvpInfo.inFFAPvPArea = (area && (area->Flags & AREA_FLAG_ARENA)) || InRatedBattleGround();
    UpdatePvPState(true);

    //Pandaria area update for monk level < 85
    if (area && getLevel() < 85 && getClass() == CLASS_MONK && GetMapId() == 870 && area->ContinentID == 870 &&
        newArea != 6081 && newArea != 6526 && newArea != 6527
        && GetZoneId() == 5841 && !isGameMaster())
        TeleportTo(870, 3818.55f, 1793.18f, 950.35f, GetOrientation());

    UpdateAreaDependentAuras(newArea);

    // previously this was in UpdateZone (but after UpdateArea) so nothing will break
    pvpInfo.inNoPvPArea = false;
    if (area && area->IsSanctuary())    // in sanctuary
    {
        SetByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_SANCTUARY);
        pvpInfo.inNoPvPArea = true;
        CombatStopWithPets();
    }
    else
        RemoveByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_SANCTUARY);

    uint32 const l_AreaRestFlag = (GetTeam() == ALLIANCE) ? AREA_FLAG_REST_ZONE_ALLIANCE : AREA_FLAG_REST_ZONE_HORDE;
    if (area && (area->Flags & l_AreaRestFlag))
    {
        SetFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
        SetRestType(REST_TYPE_IN_FACTION_AREA);
        InnEnter(time(0), GetMapId(), 0, 0, 0);
    }
    else if (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING) && GetRestType() == REST_TYPE_IN_FACTION_AREA)
    {
        RemoveFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
        SetRestType(REST_TYPE_NO);
    }

    phaseMgr.RemoveUpdateFlag(PHASE_UPDATE_FLAG_AREA_UPDATE);

    if (l_OldArea != newArea)
    {
        uint64 l_Guid = GetGUID();

        sOutdoorPvPMgr->HandlePlayerLeaveArea(this, l_OldArea);
        sOutdoorPvPMgr->HandlePlayerEnterArea(this, newArea);

        /// Garrison phasing specific code
        if (m_Garrison && m_Garrison->GetGarrisonSiteLevelEntry() && (GetMapId() == MS::Garrison::Globals::BaseMap || GetMapId() == m_Garrison->GetGarrisonSiteLevelEntry()->MapID || GetMapId() == MS::Garrison::ShipyardMapId::Alliance || GetMapId() == MS::Garrison::ShipyardMapId::Horde))
        {
            Map * l_Map = sMapMgr->FindBaseNonInstanceMap(MS::Garrison::Globals::BaseMap);

            if (!l_Map)
                l_Map = sMapMgr->CreateBaseMap(MS::Garrison::Globals::BaseMap);

            if (l_Map)
            {
                uint32 l_DraenorBaseMap_Zone;
                uint32 l_DraenorBaseMap_Area;

                l_Map->GetZoneAndAreaId(l_DraenorBaseMap_Zone, l_DraenorBaseMap_Area, m_positionX, m_positionY, m_positionZ);
                const GarrSiteLevelEntry * l_GarrisonSiteEntry = m_Garrison->GetGarrisonSiteLevelEntry();

                if (l_DraenorBaseMap_Area != MS::Garrison::gGarrisonShipyardAreaID[m_Garrison->GetGarrisonFactionIndex()] && IsInShipyard())
                {
                    sMapMgr->AddCriticalOperation([l_Guid]() -> bool
                    {
                        Player * l_Player = sObjectAccessor->FindPlayer(l_Guid);

                        if (l_Player && l_Player->IsInWorld())
                        {
                            l_Player->_SetOutOfShipyard();
                            return true;
                        }

                        return false;
                    });
                }
                else if (l_DraenorBaseMap_Area == MS::Garrison::gGarrisonShipyardAreaID[m_Garrison->GetGarrisonFactionIndex()] && GetMapId() == MS::Garrison::Globals::BaseMap)
                {
                    sMapMgr->AddCriticalOperation([l_Guid]() -> bool
                    {
                        Player * l_Player = sObjectAccessor->FindPlayer(l_Guid);

                        if (l_Player && l_Player->IsInWorld())
                        {
                            l_Player->_SetInShipyard();
                            return true;
                        }

                        return false;
                    });
                }

                if (l_DraenorBaseMap_Area != MS::Garrison::gGarrisonInGarrisonAreaID[m_Garrison->GetGarrisonFactionIndex()] && GetMapId() == l_GarrisonSiteEntry->MapID)
                {
                    sMapMgr->AddCriticalOperation([l_Guid]() -> bool
                    {
                        Player * l_Player = HashMapHolder<Player>::Find(l_Guid);

                        if (l_Player && l_Player->IsInWorld())
                        {
                            l_Player->_GarrisonSetOut();
                            return true;
                        }

                        return false;
                    });
                }
                else if (l_DraenorBaseMap_Area == MS::Garrison::gGarrisonInGarrisonAreaID[m_Garrison->GetGarrisonFactionIndex()] && GetMapId() == MS::Garrison::Globals::BaseMap)
                {
                    sMapMgr->AddCriticalOperation([l_Guid]() -> bool
                    {
                        Player * l_Player = HashMapHolder<Player>::Find(l_Guid);

                        if (l_Player && l_Player->IsInWorld())
                        {
                            l_Player->_GarrisonSetIn();
                            return true;
                        }

                        return false;
                    });
                }
            }
        }
    }
}

void Player::_GarrisonSetIn()
{
    if (!m_Garrison)
        return;

    const GarrSiteLevelEntry * l_GarrisonSiteEntry = m_Garrison->GetGarrisonSiteLevelEntry();

    if (!l_GarrisonSiteEntry)
        return;

    Difficulty l_DungeonDiff = DifficultyNormal;
    std::swap(l_DungeonDiff, m_dungeonDifficulty);

    SwitchToPhasedMap(l_GarrisonSiteEntry->MapID);
    m_Garrison->OnPlayerEnter();

    std::swap(l_DungeonDiff, m_dungeonDifficulty);

    phaseMgr.Update();
    phaseMgr.ForceMapShiftUpdate();
}

void Player::_GarrisonSetOut()
{
    if (!m_Garrison)
        return;

    m_Garrison->OnPlayerLeave();
    m_Garrison->_SetGarrisonScript(nullptr);

    SwitchToPhasedMap(MS::Garrison::Globals::BaseMap);

    phaseMgr.Update();
    phaseMgr.ForceMapShiftUpdate();
}

void Player::_SetInShipyard()
{
    if (!m_Garrison || !m_Garrison->HasShipyard())
        return;

    Difficulty l_DungeonDiff = DifficultyNormal;
    std::swap(l_DungeonDiff, m_dungeonDifficulty);

    SwitchToPhasedMap(m_Garrison->GetShipyardMapId());

    std::swap(l_DungeonDiff, m_dungeonDifficulty);

    phaseMgr.Update();
    phaseMgr.ForceMapShiftUpdate();
}

void Player::_SetOutOfShipyard()
{
    if (!m_Garrison || !m_Garrison->HasShipyard())
        return;

    SwitchToPhasedMap(MS::Garrison::Globals::BaseMap);

    phaseMgr.Update();
    phaseMgr.ForceMapShiftUpdate();
}

void Player::UpdateZone(uint32 newZone, uint32 newArea)
{
    phaseMgr.AddUpdateFlag(PHASE_UPDATE_FLAG_ZONE_UPDATE);

    if (m_zoneUpdateId != newZone)
    {
        sOutdoorPvPMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
        sOutdoorPvPMgr->HandlePlayerEnterZone(this, newZone);
        sBattlefieldMgr->HandlePlayerLeaveZone(this, m_zoneUpdateId);
        sBattlefieldMgr->HandlePlayerEnterZone(this, newZone);
        SendInitWorldStates(newZone, newArea);              // only if really enters to new zone, not just area change, works strange...
    }

    // group update
    if (Group* group = GetGroup())
    {
        SetGroupUpdateFlag(GROUP_UPDATE_FULL);
        if (GetSession() && group->isLFGGroup() && sLFGMgr->IsTeleported(GetGUID()))
        {
            for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
            {
                if (Player* member = itr->getSource())
                    GetSession()->SendNameQueryOpcode(member->GetGUID());
            }
        }
    }

    uint32 l_OldZone  = m_zoneUpdateId;
    m_zoneUpdateId    = newZone;
    m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;

    // zone changed, so area changed as well, update it
    UpdateArea(newArea);

    sScriptMgr->OnPlayerUpdateZone(this, newZone, l_OldZone, newArea);

    AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
    if (!zone)
        return;

    if (sWorld->getBoolConfig(CONFIG_WEATHER) && !HasAuraType(SPELL_AURA_FORCE_WEATHER))
    {
        if (Weather* weather = WeatherMgr::FindWeather(zone->ID))
            weather->SendWeatherUpdateToPlayer(this);
        else
        {
            if (!WeatherMgr::AddWeather(zone->ID))
            {
                // send fine weather packet to remove old zone's weather
                WeatherMgr::SendFineWeatherUpdateToPlayer(this);
            }
        }
    }

    // in PvP, any not controlled zone (except zone->team == 6, default case)
    // in PvE, only opposition team capital
    switch (zone->FactionGroupMask)
    {
        case AREATEAM_ALLY:
            pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld->IsPvPRealm() || zone->Flags & AREA_FLAG_CAPITAL);
            break;
        case AREATEAM_HORDE:
            pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld->IsPvPRealm() || zone->Flags & AREA_FLAG_CAPITAL);
            break;
        case AREATEAM_NONE:
            // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
            pvpInfo.inHostileArea = sWorld->IsPvPRealm() || InBattleground() || zone->Flags & AREA_FLAG_WINTERGRASP;
            break;
        default:                                            // 6 in fact
            pvpInfo.inHostileArea = false;
            break;
    }

    if (zone->Flags & AREA_FLAG_CAPITAL)                     // Is in a capital city
    {
        if (!pvpInfo.inHostileArea || zone->IsSanctuary())
        {
            SetFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
            SetRestType(REST_TYPE_IN_CITY);
            InnEnter(time(0), GetMapId(), 0, 0, 0);
        }
        pvpInfo.inNoPvPArea = true;
    }
    else
    {
        if (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
        {
            if (GetRestType() == REST_TYPE_IN_TAVERN)        // Still inside a tavern or has recently left
            {
                // Remove rest state if we have recently left a tavern.
                if (GetMapId() != GetInnPosMapId() || GetExactDist(GetInnPosX(), GetInnPosY(), GetInnPosZ()) > 1.0f)
                {
                    RemoveFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
                    SetRestType(REST_TYPE_NO);
                }
            }
            else if (GetRestType() != REST_TYPE_IN_FACTION_AREA) // handled in UpdateArea
            {
                // Recently left a capital city
                RemoveFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
                SetRestType(REST_TYPE_NO);
            }
        }
    }

    UpdatePvPState();

    // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
    // if player resurrected at teleport this will be applied in resurrect code
    if (isAlive())
        DestroyZoneLimitedItem(true, newZone);

    // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
    AutoUnequipOffhandIfNeed();

    // recent client version not send leave/join channel packets for built-in local channels
    UpdateLocalChannels(newZone);

    UpdateZoneDependentAuras(newZone);

    phaseMgr.RemoveUpdateFlag(PHASE_UPDATE_FLAG_ZONE_UPDATE);
}

//If players are too far away from the duel flag... they lose the duel
void Player::CheckDuelDistance(time_t currTime)
{
    if (!m_Duel)
        return;

    uint64 duelFlagGUID = GetGuidValue(PLAYER_FIELD_DUEL_ARBITER);
    GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
    if (!obj)
        return;

    if (m_Duel->outOfBound == 0)
    {
        if (!IsWithinDistInMap(obj, 100))
        {
            m_Duel->outOfBound = currTime;

            WorldPacket data(SMSG_DUEL_OUT_OF_BOUNDS, 0);
            GetSession()->SendPacket(&data);
        }
    }
    else
    {
        if (IsWithinDistInMap(obj, 80))
        {
            m_Duel->outOfBound = 0;

            WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
            GetSession()->SendPacket(&data);
        }
        else if (currTime >= (m_Duel->outOfBound+10))
            DuelComplete(DUEL_FLED);
    }
}

bool Player::IsOutdoorPvPActive()
{
    return isAlive() && !HasInvisibilityAura() && !HasStealthAura() && IsPvP() && !HasUnitMovementFlag(MOVEMENTFLAG_FLYING) && !isInFlight();
}

void Player::DuelComplete(DuelCompleteType p_DuelType)
{
    // duel not requested
    if (!m_Duel)
        return;

    // Say "duel has been canceled"
    if (p_DuelType == DUEL_INTERRUPTED)
    {
        WorldPacket l_Data(SMSG_DUEL_COMPLETE, (1));
        l_Data.WriteBit(m_Duel->started);       ///< Started
        l_Data.FlushBits();
        GetSession()->SendPacket(&l_Data);

        if (m_Duel->opponent->GetSession())
            m_Duel->opponent->GetSession()->SendPacket(&l_Data);
    }


    if (p_DuelType != DUEL_INTERRUPTED)
    {
        /// Opponent is always the winner ...
        std::string l_BeatenName = GetName();
        std::string l_WinnerName = m_Duel->opponent->GetName();

        WorldPacket l_Data(SMSG_DUEL_WINNER);
        l_Data.WriteBits(l_WinnerName.size(), 6);               ///< WinnerName Size
        l_Data.WriteBits(l_BeatenName.size(), 6);               ///< BeatenName Size
        l_Data.WriteBit(p_DuelType == DUEL_WON ? 0 : 1);        ///< Fled
        l_Data << uint32(g_RealmID);                            ///< WinnerVirtualRealmAddress
        l_Data << uint32(g_RealmID);                            ///< BeatenVirtualRealmAddress
        l_Data.WriteString(l_WinnerName);                       ///< WinnerName
        l_Data.WriteString(l_BeatenName);                       ///< BeatenName

        SendMessageToSet(&l_Data, true);
    }

    sScriptMgr->OnPlayerDuelEnd(m_Duel->opponent, this, p_DuelType);

    switch (p_DuelType)
    {
        case DUEL_FLED:
            // if initiator and opponent are on the same team
            // or initiator and opponent are not PvP enabled, forcibly stop attacking
            if (m_Duel->initiator->GetTeam() == m_Duel->opponent->GetTeam())
            {
                m_Duel->initiator->AttackStop();
                m_Duel->opponent->AttackStop();
            }
            else
            {
                if (!m_Duel->initiator->IsPvP())
                    m_Duel->initiator->AttackStop();
                if (!m_Duel->opponent->IsPvP())
                    m_Duel->opponent->AttackStop();
            }
            break;
        case DUEL_WON:
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
            if (m_Duel->opponent)
            {
                 m_Duel->opponent->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);

                //Credit for quest Death's Challenge
                if (getClass() == CLASS_DEATH_KNIGHT && m_Duel->opponent->GetQuestStatus(12733) == QUEST_STATUS_INCOMPLETE)
                    m_Duel->opponent->CastSpell(m_Duel->opponent, 52994, true);
            }
            break;
        default:
            break;
    }

    // Victory emote spell
    if (p_DuelType != DUEL_INTERRUPTED && m_Duel->opponent)
        m_Duel->opponent->CastSpell(m_Duel->opponent, 52852, true);

    //Remove Duel Flag object
    GameObject* obj = GetMap()->GetGameObject(GetGuidValue(PLAYER_FIELD_DUEL_ARBITER));
    if (obj)
        m_Duel->initiator->RemoveGameObject(obj, true);

    /* remove auras */
    AuraApplicationMap &itsAuras = m_Duel->opponent->GetAppliedAuras();
    for (AuraApplicationMap::iterator i = itsAuras.begin(); i != itsAuras.end();)
    {
        Aura const* aura = i->second->GetBase();
        if (!i->second->IsPositive() && aura->GetCasterGUID() == GetGUID() && aura->GetApplyTime() >= m_Duel->startTime && !i->second->GetRemoveMode())
            m_Duel->opponent->RemoveAura(i);
        else
            ++i;
    }

    AuraApplicationMap &myAuras = GetAppliedAuras();
    for (AuraApplicationMap::iterator i = myAuras.begin(); i != myAuras.end();)
    {
        Aura const* aura = i->second->GetBase();
        if (!i->second->IsPositive() && m_Duel->opponent != nullptr && aura->GetCasterGUID() == m_Duel->opponent->GetGUID() && aura->GetApplyTime() >= m_Duel->startTime && !i->second->GetRemoveMode())
            RemoveAura(i);
        else
            ++i;
    }

    // cleanup combo points
    ClearComboPoints();
    m_Duel->opponent->ClearComboPoints();

    SendClearLossOfControl();
    m_Duel->opponent->SendClearLossOfControl();

    // Honor points after duel (the winner) - ImpConfig
    if (uint32 amount = sWorld->getIntConfig(CONFIG_HONOR_AFTER_DUEL))
        m_Duel->opponent->RewardHonor(NULL, 1, amount);

    //cleanups
    SetGuidValue(PLAYER_FIELD_DUEL_ARBITER, 0);
    SetUInt32Value(PLAYER_FIELD_DUEL_TEAM, 0);
    m_Duel->opponent->SetGuidValue(PLAYER_FIELD_DUEL_ARBITER, 0);
    m_Duel->opponent->SetUInt32Value(PLAYER_FIELD_DUEL_TEAM, 0);

    delete m_Duel->opponent->m_Duel;
    m_Duel->opponent->m_Duel = NULL;
    delete m_Duel;
    m_Duel = NULL;
}

//---------------------------------------------------------//
void Player::_ApplyItemMods(Item* item, uint8 slot, bool apply)
{
    if (slot >= INVENTORY_SLOT_BAG_END || !item)
        return;

    ItemTemplate const* proto = item->GetTemplate();

    if (!proto)
        return;

    // not apply/remove mods for broken item
    if (item->CantBeUse())
        return;

    sLog->outInfo(LOG_FILTER_PLAYER_ITEMS, "applying mods for item %u ", item->GetGUIDLow());

    uint8 attacktype = Player::GetAttackBySlot(slot);

    if (proto->Socket[0].Color)                              //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
        CorrectMetaGemEnchants(slot, apply);

    if (attacktype < WeaponAttackType::MaxAttack)
        _ApplyWeaponDependentAuraMods(item, WeaponAttackType(attacktype), apply);

    _ApplyItemBonuses(item, slot, apply);
    ApplyItemEquipSpell(item, apply);
    ApplyEnchantment(item, apply);
    _ApplyItemModifications(item, slot, apply);
}

void Player::_ApplyItemModifications(Item const* p_Item, uint8 p_Slot, bool p_Apply, uint32 p_RescaleToItemLevel)
{
    if (p_Slot >= INVENTORY_SLOT_BAG_END || !p_Item)
        return;

    ItemTemplate const* l_Proto = p_Item->GetTemplate();
    if (!l_Proto)
        return;

    if (!p_Item->GetAllItemBonuses().size())
        return;

     for (auto& l_ItemBonusList : p_Item->GetAllItemBonuses())
     {
        if (!l_ItemBonusList)
            continue;

        std::vector<ItemBonusEntry const*> const* l_BonusList = GetItemBonusesByID(l_ItemBonusList);
        for (uint32 i = 0; i < l_BonusList->size(); i++)
        {
            ItemBonusEntry const* l_ItemBonus = (*l_BonusList)[i];

            if (!l_ItemBonus)
                continue;

            _ApplyItemModification(p_Item, l_ItemBonus, p_Slot, p_Apply, p_RescaleToItemLevel);
        }
     }
}

void Player::_ApplyItemModification(Item const* p_Item, ItemBonusEntry const* p_ItemBonusEntry, uint8 p_Slot, bool p_Apply, uint32 p_RescaleToItemLevel)
{
    if (p_Slot >= INVENTORY_SLOT_BAG_END || !p_Item)
        return;

    ItemTemplate const* l_Proto = p_Item->GetTemplate();
    if (!l_Proto)
        return;

    uint32 ilvl = m_itemScale[p_Slot] ? m_itemScale[p_Slot] : GetEquipItemLevelFor(l_Proto, p_Item);

    if (ilvl == p_RescaleToItemLevel)
        return;

    switch (p_ItemBonusEntry->Type)
    {
        case ITEM_BONUS_ADD_STAT:
        {
            bool l_ApplyStats = p_RescaleToItemLevel < ilvl && p_RescaleToItemLevel ? !p_Apply : p_Apply;
            uint32 l_Stat = p_ItemBonusEntry->Value[0];
            int32 l_ScalingValue = p_ItemBonusEntry->Value[1];
            int32 l_StatValue = 0;

            if (!p_RescaleToItemLevel)
                l_StatValue = l_Proto->CalculateStatScaling(l_ScalingValue, 0.0f, ilvl);
            else
                l_StatValue = abs(int32(l_Proto->CalculateStatScaling(l_ScalingValue, 0.0f, p_RescaleToItemLevel) - l_Proto->CalculateStatScaling(l_ScalingValue, 0.0f, ilvl)));

            switch (l_Stat)
            {
                case ITEM_MOD_MANA:
                    HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_HEALTH:
                    HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_AGILITY:
                {
                    if (GetPrimaryStat() != STAT_AGILITY && GetSpecializationId())
                        break;

                    HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    ApplyStatBuffMod(STAT_AGILITY, float(l_StatValue), l_ApplyStats);
                    break;
                }
                case ITEM_MOD_STRENGTH:
                {
                    if (GetPrimaryStat() != STAT_STRENGTH && GetSpecializationId())
                        break;

                    HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    ApplyStatBuffMod(STAT_STRENGTH, float(l_StatValue), l_ApplyStats);
                    break;
                }
                case ITEM_MOD_INTELLECT:
                {
                    if (GetPrimaryStat() != STAT_INTELLECT && GetSpecializationId())
                        break;

                    HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    ApplyStatBuffMod(STAT_INTELLECT, float(l_StatValue), l_ApplyStats);
                    break;
                }
                case ITEM_MOD_SPIRIT:
                {
                    if (GetPrimaryStat() != STAT_INTELLECT && GetSpecializationId())
                        break;

                    HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    ApplyStatBuffMod(STAT_SPIRIT, float(l_StatValue), l_ApplyStats);
                    break;
                }
                case ITEM_MOD_STAMINA:
                    HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    ApplyStatBuffMod(STAT_STAMINA, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_DODGE_RATING:
                    ApplyRatingMod(CR_DODGE, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_PARRY_RATING:
                    ApplyRatingMod(CR_PARRY, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_BLOCK_RATING:
                    ApplyRatingMod(CR_BLOCK, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_CRIT_RATING:
                    ApplyRatingMod(CR_CRIT_MELEE, int32(l_StatValue), l_ApplyStats);
                    ApplyRatingMod(CR_CRIT_RANGED, int32(l_StatValue), l_ApplyStats);
                    ApplyRatingMod(CR_CRIT_SPELL, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_RESILIENCE_RATING:
                    ApplyRatingMod(CR_RESILIENCE_PLAYER_DAMAGE_TAKEN, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_HASTE_RATING:
                    ApplyRatingMod(CR_HASTE_MELEE, int32(l_StatValue), l_ApplyStats);
                    ApplyRatingMod(CR_HASTE_RANGED, int32(l_StatValue), l_ApplyStats);
                    ApplyRatingMod(CR_HASTE_SPELL, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_ATTACK_POWER:
                    HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(l_StatValue), l_ApplyStats);
                    HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_VERSATILITY_RATING:
                    ApplyRatingMod(CR_VERSATILITY_DAMAGE_DONE, int32(l_StatValue), l_ApplyStats);
                    ApplyRatingMod(CR_VERSATILITY_DAMAGE_TAKEN, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_MANA_REGENERATION:
                    ApplyManaRegenBonus(int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_SPELL_POWER:
                    ApplySpellPowerBonus(int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_HEALTH_REGEN:
                    ApplyHealthRegenBonus(int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_MASTERY_RATING:
                    ApplyRatingMod(CR_MASTERY, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_EXTRA_ARMOR:
                    HandleStatModifier(UNIT_MOD_BONUS_ARMOR, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    UpdateArmor();
                    break;
                case ITEM_MOD_FIRE_RESISTANCE:
                    HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_FROST_RESISTANCE:
                    HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_HOLY_RESISTANCE:
                    HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_SHADOW_RESISTANCE:
                    HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_NATURE_RESISTANCE:
                    HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_ARCANE_RESISTANCE:
                    HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_PVP_POWER:
                    ApplyRatingMod(CR_PVP_POWER, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_MULTISTRIKE_RATING:
                    ApplyRatingMod(CR_MULTISTRIKE, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_SPEED_RATING:
                    ApplyRatingMod(CR_SPEED, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_LEECH_RATING:
                    ApplyRatingMod(CR_LIFESTEAL, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_AVOIDANCE_RATING:
                    ApplyRatingMod(CR_AVOIDANCE, int32(l_StatValue), l_ApplyStats);
                    break;
                case ITEM_MOD_DYNAMIC_STAT_AGI_STR_INT:
                {
                    Stats stat = GetPrimaryStat();
                    HandleStatModifier((UnitMods)stat, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    ApplyStatBuffMod(stat, float(l_StatValue), l_ApplyStats);
                    break;
                }
                case ITEM_MOD_DYNAMIC_STAT_AGI_STR:
                {
                    Stats stat = GetPrimaryStat();
                    if (stat != STAT_AGILITY && stat != STAT_STRENGTH)
                        break;

                    HandleStatModifier((UnitMods)stat, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    ApplyStatBuffMod(stat, float(l_StatValue), l_ApplyStats);
                    break;
                }
                case ITEM_MOD_DYNAMIC_STAT_AGI_INT:
                {
                    Stats stat = GetPrimaryStat();
                    if (stat != STAT_AGILITY && stat != STAT_INTELLECT)
                        break;

                    HandleStatModifier((UnitMods)stat, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    ApplyStatBuffMod(stat, float(l_StatValue), l_ApplyStats);
                    break;
                }
                case ITEM_MOD_DYNAMIC_STAT_STR_INT:
                {
                    Stats stat = GetPrimaryStat();
                    if (stat != STAT_INTELLECT && stat != STAT_STRENGTH)
                        break;

                    HandleStatModifier((UnitMods)stat, BASE_VALUE, float(l_StatValue), l_ApplyStats);
                    ApplyStatBuffMod(stat, float(l_StatValue), l_ApplyStats);
                    break;
                }
            }
        }
    }
}

void Player::_ApplyItemBonuses(Item const* item, uint8 slot, bool apply, uint32 rescaleToItemLevel)
{
    if (slot >= INVENTORY_SLOT_BAG_END || !item)
        return;

    ItemTemplate const* proto = item->GetTemplate();
    if (!proto)
        return;

    if (!m_itemScale[slot] && apply)
        m_itemScale[slot] = GetEquipItemLevelFor(proto, item);

    uint32 ilvl = m_itemScale[slot];

    if (!apply && !rescaleToItemLevel)
        m_itemScale[slot] = 0;

    if (ilvl == rescaleToItemLevel)
        return;

    bool applyStats = rescaleToItemLevel < ilvl && rescaleToItemLevel ? !apply : apply;

    for (uint8 i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
    {
        uint32 statType;
        int32 val;

        if (!rescaleToItemLevel)
        {
            statType = proto->ItemStat[i].ItemStatType;
            val = (ilvl == 1 && rescaleToItemLevel == 0) ? proto->ItemStat[i].ItemStatValue : proto->CalculateStatScaling(i, ilvl);
        }
        else
        {
            statType = proto->ItemStat[i].ItemStatType;
            val = abs(int32(proto->CalculateStatScaling(i, rescaleToItemLevel) - proto->CalculateStatScaling(i, ilvl)));

            if (proto->ItemStat[i].ItemStatValue < 0)
                val = -val;
        }

        if (val == 0)
            continue;

        switch (statType)
        {
            case ITEM_MOD_MANA:
                HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), applyStats);
                break;
            case ITEM_MOD_HEALTH:
                HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), applyStats);
                break;
            case ITEM_MOD_AGILITY:
            {
                if (GetPrimaryStat() != STAT_AGILITY && GetSpecializationId())
                    break;

                HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), applyStats); 
                ApplyStatBuffMod(STAT_AGILITY, CalculatePct(val, GetModifierValue(UNIT_MOD_STAT_AGILITY, BASE_PCT_EXCLUDE_CREATE)), apply);
                break;
            }
            case ITEM_MOD_STRENGTH:
            {
                if (GetPrimaryStat() != STAT_STRENGTH && GetSpecializationId())
                    break;

                HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), applyStats);
                ApplyStatBuffMod(STAT_STRENGTH, CalculatePct(val, GetModifierValue(UNIT_MOD_STAT_STRENGTH, BASE_PCT_EXCLUDE_CREATE)), apply);
                break;
            }
            case ITEM_MOD_INTELLECT:
            {
                if (GetPrimaryStat() != STAT_INTELLECT && GetSpecializationId())
                    break;

                HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), applyStats);
                ApplyStatBuffMod(STAT_INTELLECT, CalculatePct(val, GetModifierValue(UNIT_MOD_STAT_INTELLECT, BASE_PCT_EXCLUDE_CREATE)), apply);
                break;
            }
            case ITEM_MOD_SPIRIT:
            {
                if (GetPrimaryStat() != STAT_INTELLECT && GetSpecializationId())
                    break;

                HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), applyStats);
                ApplyStatBuffMod(STAT_SPIRIT, CalculatePct(val, GetModifierValue(UNIT_MOD_STAT_SPIRIT, BASE_PCT_EXCLUDE_CREATE)), apply);
                break;
            }
            case ITEM_MOD_STAMINA:
                HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), applyStats);
                ApplyStatBuffMod(STAT_STAMINA, CalculatePct(val, GetModifierValue(UNIT_MOD_STAT_STAMINA, BASE_PCT_EXCLUDE_CREATE)), apply);
                break;
            case ITEM_MOD_DODGE_RATING:
                ApplyRatingMod(CR_DODGE, int32(val), applyStats);
                break;
            case ITEM_MOD_PARRY_RATING:
                ApplyRatingMod(CR_PARRY, int32(val), applyStats);
                break;
            case ITEM_MOD_BLOCK_RATING:
                ApplyRatingMod(CR_BLOCK, int32(val), applyStats);
                break;
            case ITEM_MOD_CRIT_RATING:
                ApplyRatingMod(CR_CRIT_MELEE, int32(val), applyStats);
                ApplyRatingMod(CR_CRIT_RANGED, int32(val), applyStats);
                ApplyRatingMod(CR_CRIT_SPELL, int32(val), applyStats);
                break;
            case ITEM_MOD_RESILIENCE_RATING:
                ApplyRatingMod(CR_RESILIENCE_PLAYER_DAMAGE_TAKEN, int32(val), applyStats);
                break;
            case ITEM_MOD_HASTE_RATING:
                ApplyRatingMod(CR_HASTE_MELEE, int32(val), applyStats);
                ApplyRatingMod(CR_HASTE_RANGED, int32(val), applyStats);
                ApplyRatingMod(CR_HASTE_SPELL, int32(val), applyStats);
                break;
            case ITEM_MOD_ATTACK_POWER:
                HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), applyStats);
                HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), applyStats);
                break;
            case ITEM_MOD_VERSATILITY_RATING:
                ApplyRatingMod(CR_VERSATILITY_DAMAGE_DONE, int32(val), applyStats);
                ApplyRatingMod(CR_VERSATILITY_DAMAGE_TAKEN, int32(val), applyStats);
                break;
            case ITEM_MOD_MANA_REGENERATION:
                ApplyManaRegenBonus(int32(val), applyStats);
                break;
            case ITEM_MOD_SPELL_POWER:
                ApplySpellPowerBonus(int32(val), applyStats);
                break;
            case ITEM_MOD_HEALTH_REGEN:
                ApplyHealthRegenBonus(int32(val), applyStats);
                break;
            case ITEM_MOD_MASTERY_RATING:
                ApplyRatingMod(CR_MASTERY, int32(val), applyStats);
                break;
            case ITEM_MOD_EXTRA_ARMOR:
                HandleStatModifier(UNIT_MOD_BONUS_ARMOR, BASE_VALUE, float(val), applyStats);
                UpdateArmor();
                break;
            case ITEM_MOD_FIRE_RESISTANCE:
                HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(val), applyStats);
                break;
            case ITEM_MOD_FROST_RESISTANCE:
                HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(val), applyStats);
                break;
            case ITEM_MOD_HOLY_RESISTANCE:
                HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(val), applyStats);
                break;
            case ITEM_MOD_SHADOW_RESISTANCE:
                HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(val), applyStats);
                break;
            case ITEM_MOD_NATURE_RESISTANCE:
                HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(val), applyStats);
                break;
            case ITEM_MOD_ARCANE_RESISTANCE:
                HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(val), applyStats);
                break;
            case ITEM_MOD_PVP_POWER:
                ApplyRatingMod(CR_PVP_POWER, int32(val), applyStats);
                break;
            case ITEM_MOD_MULTISTRIKE_RATING:
                ApplyRatingMod(CR_MULTISTRIKE, int32(val), applyStats);
                break;
            case ITEM_MOD_SPEED_RATING:
                ApplyRatingMod(CR_SPEED, int32(val), applyStats);
                break;
            case ITEM_MOD_LEECH_RATING:
                ApplyRatingMod(CR_LIFESTEAL, int32(val), applyStats);
                break;
            case ITEM_MOD_AVOIDANCE_RATING:
                ApplyRatingMod(CR_AVOIDANCE, int32(val), applyStats);
                break;
            case ITEM_MOD_DYNAMIC_STAT_AGI_STR_INT:
            {
                Stats stat = GetPrimaryStat();
                HandleStatModifier((UnitMods)stat, BASE_VALUE, float(val), applyStats);
                ApplyStatBuffMod(stat, float(val), applyStats);
                break;
            }
            case ITEM_MOD_DYNAMIC_STAT_AGI_STR:
            {
                Stats stat = GetPrimaryStat();
                if (stat != STAT_AGILITY && stat != STAT_STRENGTH)
                    break;

                HandleStatModifier((UnitMods)stat, BASE_VALUE, float(val), applyStats);
                ApplyStatBuffMod(stat, float(val), applyStats);
                break;
            }
            case ITEM_MOD_DYNAMIC_STAT_AGI_INT:
            {
                Stats stat = GetPrimaryStat();
                if (stat != STAT_AGILITY && stat != STAT_INTELLECT)
                    break;

                HandleStatModifier((UnitMods)stat, BASE_VALUE, float(val), applyStats);
                ApplyStatBuffMod(stat, float(val), applyStats);
                break;
            }
            case ITEM_MOD_DYNAMIC_STAT_STR_INT:
            {
                Stats stat = GetPrimaryStat();
                if (stat != STAT_INTELLECT && stat != STAT_STRENGTH)
                    break;

                HandleStatModifier((UnitMods)stat, BASE_VALUE, float(val), applyStats);
                ApplyStatBuffMod(stat, float(val), applyStats);
                break;
            }
        }
    }

    uint32 armor = proto->CalculateArmorScaling(ilvl);
    if (rescaleToItemLevel)
        armor = abs(int32(proto->CalculateArmorScaling(ilvl) - proto->CalculateArmorScaling(rescaleToItemLevel)));

    if (armor)
    {
        UnitModifierType modType = TOTAL_VALUE;
        if (proto->Class == ITEM_CLASS_ARMOR)
        {
            switch (proto->SubClass)
            {
                case ITEM_SUBCLASS_ARMOR_CLOTH:
                case ITEM_SUBCLASS_ARMOR_LEATHER:
                case ITEM_SUBCLASS_ARMOR_MAIL:
                case ITEM_SUBCLASS_ARMOR_PLATE:
                case ITEM_SUBCLASS_ARMOR_SHIELD:
                    modType = BASE_VALUE;
                break;
            }
        }
        HandleStatModifier(UNIT_MOD_ARMOR, modType, float(armor), applyStats);
    }

    if (!proto->IsWeapon())
        return;

    WeaponAttackType attType = WeaponAttackType::BaseAttack;

    if (slot == EQUIPMENT_SLOT_MAINHAND && (
        proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
        proto->InventoryType == INVTYPE_RANGEDRIGHT))
    {
        attType = WeaponAttackType::RangedAttack;
    }
    else if (slot == EQUIPMENT_SLOT_OFFHAND)
        attType = WeaponAttackType::OffAttack;

    uint32 minDamage = 0;
    uint32 maxDamage = 0;

    if (apply)
        proto->CalculateMinMaxDamageScaling(rescaleToItemLevel ? rescaleToItemLevel : ilvl, minDamage, maxDamage);

    if (CanUseAttackType(attType))
        _ApplyWeaponDamage(slot, item, apply, minDamage, maxDamage);

    // Dual Wield penalty
    if (CanModifyStats())
    {
        if (attType == WeaponAttackType::OffAttack)
            UpdateDamagePhysical(WeaponAttackType::BaseAttack, !apply);
        else if (attType == WeaponAttackType::BaseAttack && CanUseAttackType(WeaponAttackType::OffAttack))
            UpdateDamagePhysical(WeaponAttackType::OffAttack, !apply);
    }
}

void Player::_ApplyWeaponDamage(uint8 slot, Item const* item, bool apply, uint32 minDamage, uint32 maxDamage)
{
    ItemTemplate const* proto = item->GetTemplate();
    WeaponAttackType attType = WeaponAttackType::BaseAttack;

    if (slot == EQUIPMENT_SLOT_MAINHAND && (
        proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
        proto->InventoryType == INVTYPE_RANGEDRIGHT))
    {
        attType = WeaponAttackType::RangedAttack;
    }
    else if (slot == EQUIPMENT_SLOT_OFFHAND)
    {
        attType = WeaponAttackType::OffAttack;
    }

    if (!maxDamage && apply)
        proto->CalculateMinMaxDamageScaling(GetEquipItemLevelFor(proto, item), minDamage, maxDamage);

    if (!minDamage && maxDamage && apply)
        minDamage = maxDamage;

    float damage = apply ? minDamage : 0;
    SetBaseWeaponDamage(attType, MINDAMAGE, damage);
    damage = apply ? maxDamage : 0;
    SetBaseWeaponDamage(attType, MAXDAMAGE, damage);

    if (proto->Delay && !IsInFeralForm())
    {
        if (slot == EQUIPMENT_SLOT_MAINHAND && (
        proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
        proto->InventoryType == INVTYPE_RANGEDRIGHT))
            SetAttackTime(WeaponAttackType::RangedAttack, apply ? proto->Delay: BASE_ATTACK_TIME);
        else if (slot == EQUIPMENT_SLOT_MAINHAND)
            SetAttackTime(WeaponAttackType::BaseAttack, apply ? proto->Delay: BASE_ATTACK_TIME);
        else if (slot == EQUIPMENT_SLOT_OFFHAND)
            SetAttackTime(WeaponAttackType::OffAttack, apply ? proto->Delay: BASE_ATTACK_TIME);
    }

    if (CanModifyStats())
        UpdateDamagePhysical(attType);
}

void Player::_ApplyWeaponDependentAuraMods(Item* item, WeaponAttackType attackType, bool apply)
{
    AuraEffectList const& auraCritList = GetAuraEffectsByType(SPELL_AURA_MOD_WEAPON_CRIT_PERCENT);
    for (AuraEffectList::const_iterator itr = auraCritList.begin(); itr != auraCritList.end(); ++itr)
        _ApplyWeaponDependentAuraCritMod(item, attackType, *itr, apply);

    AuraEffectList const& auraDamageFlatList = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE);
    for (AuraEffectList::const_iterator itr = auraDamageFlatList.begin(); itr != auraDamageFlatList.end(); ++itr)
        _ApplyWeaponDependentAuraDamageMod(item, attackType, *itr, apply);

    AuraEffectList const& auraDamagePctList = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
    for (AuraEffectList::const_iterator itr = auraDamagePctList.begin(); itr != auraDamagePctList.end(); ++itr)
        _ApplyWeaponDependentAuraDamageMod(item, attackType, *itr, apply);

    _ApplyWeaponDependentAuraSpellModifier(item, attackType, apply);
}

void Player::_ApplyWeaponDependentAuraCritMod(Item* item, WeaponAttackType attackType, AuraEffect const* aura, bool apply)
{
    // don't apply mod if item is broken or cannot be used
    if (item->CantBeUse() || !CanUseAttackType(attackType))
        return;

    // generic not weapon specific case processes in aura code
    if (aura->GetSpellInfo()->EquippedItemClass == -1)
        return;

    BaseModGroup mod = BASEMOD_END;
    switch (attackType)
    {
        case WeaponAttackType::BaseAttack:   mod = CRIT_PERCENTAGE;        break;
        case WeaponAttackType::OffAttack:    mod = OFFHAND_CRIT_PERCENTAGE;break;
        case WeaponAttackType::RangedAttack: mod = RANGED_CRIT_PERCENTAGE; break;
        default: return;
    }

    if (item->IsFitToSpellRequirements(aura->GetSpellInfo()))
        HandleBaseModValue(mod, FLAT_MOD, float (aura->GetAmount()), apply);
}

void Player::_ApplyWeaponDependentAuraDamageMod(Item* item, WeaponAttackType attackType, AuraEffect const* aura, bool apply)
{
    // don't apply mod if item is broken or cannot be used
    if (item->CantBeUse() || !CanUseAttackType(attackType))
        return;

    // ignore spell mods for not wands
    if ((aura->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) == 0 && (getClassMask() & CLASSMASK_WAND_USERS) == 0)
        return;

    // generic not weapon specific case processes in aura code
    if (aura->GetSpellInfo()->EquippedItemClass == -1)
        return;

    UnitMods unitMod = UNIT_MOD_END;
    switch (attackType)
    {
        case WeaponAttackType::BaseAttack:   unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
        case WeaponAttackType::OffAttack:    unitMod = UNIT_MOD_DAMAGE_OFFHAND;  break;
        case WeaponAttackType::RangedAttack: unitMod = UNIT_MOD_DAMAGE_RANGED;   break;
        default: return;
    }

    UnitModifierType unitModType = TOTAL_VALUE;
    switch (aura->GetAuraType())
    {
        case SPELL_AURA_MOD_DAMAGE_DONE:         unitModType = TOTAL_VALUE; break;
        case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT;   break;
        default: return;
    }

    if (item->IsFitToSpellRequirements(aura->GetSpellInfo()))
    {
        HandleStatModifier(unitMod, unitModType, float(aura->GetAmount()), apply);
        if (unitModType == TOTAL_VALUE)
            ApplyModUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS, aura->GetAmount(), apply);
    }
}

void Player::_ApplyWeaponDependentAuraSpellModifier(Item* item, WeaponAttackType attackType, bool apply)
{
    // don't apply mod if item is broken or cannot be used
    if (item->CantBeUse() || !CanUseAttackType(attackType))
        return;

    switch (getClass())
    {
        case CLASS_DEATH_KNIGHT:
        {
            switch (GetSpecializationId())
            {
                case SPEC_DK_FROST:
                    if (getLevel() < 74)
                        break;

                    if (apply)
                    {
                        if (item->GetTemplate()->InventoryType == INVTYPE_2HWEAPON)
                        {
                            CastSpell(this, 81333, true);
                            RemoveAura(66192);
                        }
                        else if (item->GetTemplate()->InventoryType == INVTYPE_WEAPON)
                        {
                            if ((attackType == WeaponAttackType::BaseAttack && GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) ||
                                (attackType == WeaponAttackType::OffAttack && GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND)))
                            {
                                CastSpell(this, 66192, true);
                                RemoveAura(81333);
                            }
                        }
                    }
                    else
                    {
                        if (item->GetTemplate()->InventoryType == INVTYPE_2HWEAPON)
                            RemoveAura(81333);
                        else if (item->GetTemplate()->InventoryType == INVTYPE_WEAPON)
                        {
                            if ((attackType == WeaponAttackType::BaseAttack && GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) ||
                                (attackType == WeaponAttackType::OffAttack && GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND)))
                                RemoveAura(66192);
                        }
                    }
                    break;
                default:
                    break;
            }

            break;
        }
        default:
            break;
    }
}

void Player::ApplyItemEquipSpell(Item* item, bool apply, bool form_change)
{
    if (!item)
        return;

    ItemTemplate const* proto = item->GetTemplate();
    if (!proto)
        return;

    for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
    {
        _Spell const& spellData = proto->Spells[i];

        // no spell
        if (!spellData.SpellId)
            continue;

        // wrong triggering type
        if (apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
            continue;

        // check if it is valid spell
        SpellInfo const* spellproto = sSpellMgr->GetSpellInfo(spellData.SpellId);
        if (!spellproto)
            continue;

        // Item doesn't need to be equipped
        if (spellData.SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE && spellproto->HasAura(SPELL_AURA_MOD_SKILL_VALUE))
            continue;

        ApplyEquipSpell(spellproto, item, apply, form_change);
    }
}

void Player::ApplyEquipSpell(SpellInfo const* spellInfo, Item* item, bool apply, bool form_change)
{
    if (apply)
    {
        // Cannot be used in this stance/form
        if (spellInfo->CheckShapeshift(GetShapeshiftForm()) != SPELL_CAST_OK)
            return;

        if (form_change)                                    // check aura active state from other form
        {
            AuraApplicationMap const& auras = GetAppliedAuras();
            for (AuraApplicationMap::const_iterator itr = auras.lower_bound(spellInfo->Id); itr != auras.upper_bound(spellInfo->Id); ++itr)
                if (!item || itr->second->GetBase()->GetCastItemGUID() == item->GetGUID())
                    return;
        }

        sLog->outDebug(LOG_FILTER_PLAYER, "WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);

        CastSpell(this, spellInfo, true, item);
    }
    else
    {
        if (form_change)                                     // check aura compatibility
        {
            // Cannot be used in this stance/form
            if (spellInfo->CheckShapeshift(GetShapeshiftForm()) == SPELL_CAST_OK)
                return;                                     // and remove only not compatible at form change
        }

        if (item)
            RemoveAurasDueToItemSpell(item, spellInfo->Id);  // un-apply all spells, not only at-equipped
        else
            RemoveAurasDueToSpell(spellInfo->Id);           // un-apply spell (item set case)
    }
}

void Player::UpdateEquipSpellsAtFormChange()
{
    for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        if (m_items[i] && !m_items[i]->CantBeUse() && CanUseAttackType(GetAttackBySlot(i)))
        {
            ApplyItemEquipSpell(m_items[i], false, true);     // remove spells that not fit to form
            ApplyItemEquipSpell(m_items[i], true, true);      // add spells that fit form but not active
        }
    }

    // item set bonuses not dependent from item broken state
    for (size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
    {
        ItemSetEffect* eff = ItemSetEff[setindex];
        if (!eff)
            continue;

        for (uint32 y = 0; y < MAX_ITEM_SET_SPELLS; ++y)
        {
            SpellInfo const* spellInfo = eff->spells[y];
            if (!spellInfo)
                continue;

            ApplyEquipSpell(spellInfo, NULL, false, true);       // remove spells that not fit to form
            ApplyEquipSpell(spellInfo, NULL, true, true);        // add spells that fit form but not active
        }
    }
}

void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx)
{
    if (!target || !target->isAlive() || target == this)
        return;

    for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        // If usable, try to cast item spell
        if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (!item->CantBeUse() && CanUseAttackType(attType))
                if (ItemTemplate const* proto = item->GetTemplate())
                {
                    // Additional check for weapons
                    if (proto->Class == ITEM_CLASS_WEAPON)
                    {
                        // offhand item cannot proc from main hand hit etc
                        EquipmentSlots slot;
                        switch (attType)
                        {
                            case WeaponAttackType::BaseAttack:   slot = EQUIPMENT_SLOT_MAINHAND; break;
                            case WeaponAttackType::OffAttack:    slot = EQUIPMENT_SLOT_OFFHAND;  break;
                            case WeaponAttackType::RangedAttack: slot = EQUIPMENT_SLOT_MAINHAND;   break;
                            default: slot = EQUIPMENT_SLOT_END; break;
                        }
                        if (slot != i)
                            continue;
                        // Check if item is useable (forms or disarm)
                        if (attType == WeaponAttackType::BaseAttack)
                            if (!IsUseEquipedWeapon(true) && !IsInFeralForm())
                                continue;
                    }
                    CastItemCombatSpell(target, attType, procVictim, procEx, item, proto);
                }
    }
}

void Player::CastItemCombatSpell(Unit* target, WeaponAttackType attType, uint32 procVictim, uint32 procEx, Item* item, ItemTemplate const* proto)
{
    // Can do effect if any damage done to target
    if (procVictim & PROC_FLAG_TAKEN_DAMAGE)
    //if (damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE)
    {
        for (uint8 i = 0; i < MAX_ITEM_SPELLS; ++i)
        {
            _Spell const& spellData = proto->Spells[i];

            // no spell
            if (!spellData.SpellId)
                continue;

            // wrong triggering type
            if (spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
                continue;

            SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellData.SpellId);
            if (!spellInfo)
            {
                sLog->outError(LOG_FILTER_PLAYER_ITEMS, "WORLD: unknown Item spellid %i", spellData.SpellId);
                continue;
            }

            // not allow proc extra attack spell at extra attack
            if (m_extraAttacks && spellInfo->HasEffect(SPELL_EFFECT_ADD_EXTRA_ATTACKS))
                return;

            float chance = (float)spellInfo->ProcChance;

            if (proto->SpellPPMRate)
            {
                if (spellData.SpellId == 52781) // Persuasive Strike
                {
                    switch (target->GetEntry())
                    {
                        default:
                            return;
                        case 28939:
                        case 28940:
                        case 28610:
                            break;
                    }
                }
                uint32 WeaponSpeed = GetAttackTime(attType);
                chance = GetPPMProcChance(WeaponSpeed, proto->SpellPPMRate, spellInfo);
            }
            else if (chance > 100.0f)
            {
                chance = GetWeaponProcChance();
            }

            if (roll_chance_f(chance))
                CastSpell(target, spellInfo->Id, true, item);
        }
    }

    // item combat enchantments
    for (uint8 e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
    {
        if (e_slot > ENGINEERING_ENCHANTMENT_SLOT && e_slot < PROP_ENCHANTMENT_SLOT_0)    // not holding enchantment id
            continue;

        uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
        SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
        if (!pEnchant)
            continue;

        for (uint8 s = 0; s < MAX_ENCHANTMENT_SPELLS; ++s)
        {
            if (pEnchant->type[s] != ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
                continue;

            SpellEnchantProcEntry const* entry = sSpellMgr->GetSpellEnchantProcEvent(enchant_id);

            if (entry && entry->procEx)
            {
                // Check hit/crit/dodge/parry requirement
                if ((entry->procEx & procEx) == 0)
                    continue;
            }
            else
            {
                // Can do effect if any damage done to target
                if (!(procVictim & PROC_FLAG_TAKEN_DAMAGE))
                //if (!(damageInfo->procVictim & PROC_FLAG_TAKEN_ANY_DAMAGE))
                    continue;
            }

            SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(pEnchant->spellid[s]);
            if (!spellInfo)
            {
                sLog->outError(LOG_FILTER_PLAYER_ITEMS, "Player::CastItemCombatSpell(GUID: %u, name: %s, enchant: %i): unknown spell %i is casted, ignoring...",
                    GetGUIDLow(), GetName(), pEnchant->ID, pEnchant->spellid[s]);
                continue;
            }

            float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();

            if (entry)
            {
                if (entry->PPMChance)
                    chance = GetPPMProcChance(proto->Delay, entry->PPMChance, spellInfo);
                else if (entry->customChance)
                    chance = (float)entry->customChance;
            }

            // Apply spell mods
            ApplySpellMod(pEnchant->spellid[s], SPELLMOD_CHANCE_OF_SUCCESS, chance);

            if (roll_chance_f(chance))
            {
                if (spellInfo->IsPositive())
                    CastSpell(this, spellInfo, true, item);
                else
                    CastSpell(target, spellInfo, true, item);
            }
        }
    }
}

void Player::CastItemUseSpell(Item* p_Item, SpellCastTargets const& p_Targets, uint8 p_CastCount, uint32 p_Misc, uint32 p_Misc2)
{
    ItemTemplate const* l_ItemTemplate = p_Item->GetTemplate();

    /// Special learning case
    if (l_ItemTemplate->Spells[0].SpellId == 483 || l_ItemTemplate->Spells[0].SpellId == 55884)
    {
        uint32 l_LearnedSpell   = l_ItemTemplate->Spells[0].SpellId;
        uint32 l_LearningSpell  = l_ItemTemplate->Spells[1].SpellId;

        SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_LearnedSpell);
        if (!l_SpellInfo)
        {
            sLog->outError(LogFilterType::LOG_FILTER_PLAYER, "Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ", l_ItemTemplate->ItemId, l_LearnedSpell);
            SendEquipError(InventoryResult::EQUIP_ERR_INTERNAL_BAG_ERROR, p_Item, nullptr);
            return;
        }

        Spell* l_Spell          = new Spell(this, l_SpellInfo, TriggerCastFlags::TRIGGERED_NONE);
        l_Spell->m_CastItem     = p_Item;
        l_Spell->m_cast_count   = p_CastCount;  ///< Set count of casts
        l_Spell->SetSpellValue(SpellValueMod::SPELLVALUE_BASE_POINT0, l_LearningSpell);
        l_Spell->m_Misc[0] = p_Misc;
        l_Spell->m_Misc[1] = p_Misc2;
        l_Spell->prepare(&p_Targets);
        return;
    }

    /// Use triggered flag only for items with many spell casts and for not first cast
    uint8 l_Count = 0;

    /// Item enchantments spells casted at use
    for (uint8 l_Slot = 0; l_Slot < EnchantmentSlot::MAX_ENCHANTMENT_SLOT; ++l_Slot)
    {
        if (l_Slot > EnchantmentSlot::ENGINEERING_ENCHANTMENT_SLOT && l_Slot < EnchantmentSlot::PROP_ENCHANTMENT_SLOT_0)    ///< Not holding enchantment id
            continue;

        uint32 l_EnchantID = p_Item->GetEnchantmentId(EnchantmentSlot(l_Slot));
        SpellItemEnchantmentEntry const* l_ItemEnchantEntry = sSpellItemEnchantmentStore.LookupEntry(l_EnchantID);
        if (!l_ItemEnchantEntry)
            continue;

        for (uint8 l_I = 0; l_I < MAX_ENCHANTMENT_SPELLS; ++l_I)
        {
            if (l_ItemEnchantEntry->type[l_I] != ItemEnchantmentType::ITEM_ENCHANTMENT_TYPE_USE_SPELL)
                continue;

            SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_ItemEnchantEntry->spellid[l_I]);
            if (!l_SpellInfo)
            {
                sLog->outError(LogFilterType::LOG_FILTER_PLAYER, "Player::CastItemUseSpell Enchant %i, cast unknown spell %i", l_ItemEnchantEntry->ID, l_ItemEnchantEntry->spellid[l_I]);
                continue;
            }

            Spell* l_Spell          = new Spell(this, l_SpellInfo, (l_Count > 0) ? TriggerCastFlags::TRIGGERED_FULL_MASK : TriggerCastFlags::TRIGGERED_NONE);
            l_Spell->m_CastItem     = p_Item;
            l_Spell->m_cast_count   = p_CastCount;  ///< Set count of casts
            l_Spell->m_Misc[0]      = p_Misc;
            l_Spell->m_Misc[1]      = p_Misc2;
            l_Spell->prepare(&p_Targets);

            ++l_Count;
        }
    }

    /// Item spells casted at use
    for (uint8 l_I = 0; l_I < MAX_ITEM_PROTO_SPELLS; ++l_I)
    {
        _Spell const& l_SpellData = l_ItemTemplate->Spells[l_I];

        /// No spell
        if (!l_SpellData.SpellId)
            continue;

        /// Wrong triggering type
        if (l_SpellData.SpellTrigger != ItemSpelltriggerType::ITEM_SPELLTRIGGER_ON_USE)
            continue;

        SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_SpellData.SpellId);
        if (!l_SpellInfo)
        {
            sLog->outError(LogFilterType::LOG_FILTER_PLAYER, "Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring", l_ItemTemplate->ItemId, l_SpellData.SpellId);
            continue;
        }

        Spell* l_Spell            = new Spell(this, l_SpellInfo, (l_Count > 0) ? TriggerCastFlags::TRIGGERED_FULL_MASK : TriggerCastFlags::TRIGGERED_NONE);
        l_Spell->m_CastItem       = p_Item;
        l_Spell->m_cast_count     = p_CastCount;    ///< set count of casts
        l_Spell->m_Misc[0]        = p_Misc;
        l_Spell->m_Misc[1]        = p_Misc2;
        l_Spell->prepare(&p_Targets);

        ++l_Count;
    }
}

void Player::_RemoveAllItemMods()
{
    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "_RemoveAllItemMods start.");

    for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        if (m_items[i])
        {
            ItemTemplate const* proto = m_items[i]->GetTemplate();
            if (!proto)
                continue;

            // item set bonuses not dependent from item broken state
            if (proto->ItemSet)
                RemoveItemsSetItem(this, proto);

            if (m_items[i]->CantBeUse() || !CanUseAttackType(GetAttackBySlot(i)))
                continue;

            ApplyItemEquipSpell(m_items[i], false);
            ApplyEnchantment(m_items[i], false);
        }
    }

    for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        if (m_items[i])
        {
            if (m_items[i]->CantBeUse() || !CanUseAttackType(GetAttackBySlot(i)))
                continue;

            ItemTemplate const* proto = m_items[i]->GetTemplate();
            if (!proto)
                continue;

            uint32 attacktype = Player::GetAttackBySlot(i);
            if (attacktype < WeaponAttackType::MaxAttack)
                _ApplyWeaponDependentAuraMods(m_items[i], WeaponAttackType(attacktype), false);

            _ApplyItemBonuses(m_items[i], i, false);
            _ApplyItemModifications(m_items[i], i, false);
        }
    }

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "_RemoveAllItemMods complete.");
}

void Player::_ApplyAllItemMods()
{
    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "_ApplyAllItemMods start.");

    for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        if (m_items[i])
        {
            if (m_items[i]->CantBeUse() || !CanUseAttackType(GetAttackBySlot(i)))
                continue;

            ItemTemplate const* proto = m_items[i]->GetTemplate();
            if (!proto)
                continue;

            uint32 attacktype = Player::GetAttackBySlot(i);
            if (attacktype < WeaponAttackType::MaxAttack)
                _ApplyWeaponDependentAuraMods(m_items[i], WeaponAttackType(attacktype), true);

            _ApplyItemBonuses(m_items[i], i, true);
            _ApplyItemModifications(m_items[i], i, true);
        }
    }

    for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        if (m_items[i])
        {
            ItemTemplate const* proto = m_items[i]->GetTemplate();
            if (!proto)
                continue;

            // item set bonuses not dependent from item broken state
            if (proto->ItemSet)
                AddItemsSetItem(this, m_items[i]);

            if (m_items[i]->CantBeUse() || !CanUseAttackType(GetAttackBySlot(i)))
                continue;

            ApplyItemEquipSpell(m_items[i], true);
            ApplyEnchantment(m_items[i], true);
        }
    }

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "_ApplyAllItemMods complete.");
}

/*  If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
    Called by remove insignia spell effect    */
void Player::RemovedInsignia(Player* looterPlr)
{
    if (!GetBattlegroundId() && GetMapId() != 1191) ///< Specific handle for Ashran too
        return;

    // If not released spirit, do it !
    if (m_deathTimer > 0)
    {
        m_deathTimer = 0;
        BuildPlayerRepop();
        RepopAtGraveyard();
    }

    // We have to convert player corpse to bones, not to be able to resurrect there
    // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
    Corpse* bones = sObjectAccessor->ConvertCorpseForPlayer(GetGUID(), true);
    if (!bones)
        return;

    // Now we must make bones lootable, and send player loot
    bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);

    // We store the level of our player in the gold field
    // We retrieve this information at Player::SendLoot()
    bones->loot.Gold = getLevel();
    bones->lootRecipient = looterPlr;
    looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
}

void Player::SendLootRelease(uint64 p_LootGuid)
{
    uint64 l_LootObject = MAKE_NEW_GUID(GUID_LOPART(p_LootGuid), 0, HIGHGUID_LOOT);

    WorldPacket data(SMSG_LOOT_RELEASE);
    data.appendPackGUID(l_LootObject);
    data.appendPackGUID(p_LootGuid);

    SendDirectMessage(&data);
}

void Player::SendLoot(uint64 p_Guid, LootType p_LootType, bool p_FetchLoot)
{
    if (uint64 l_Guid = GetLootGUID())
        m_session->DoLootRelease(l_Guid);

    uint64 l_PlayerGuid = GetGUID();
    Loot* l_Loot = 0;
    PermissionTypes l_Permission = ALL_PERMISSION;

    if (IS_GAMEOBJECT_GUID(p_Guid))
    {
        GameObject* l_GameObject = GetMap()->GetGameObject(p_Guid);

        /// Not check distance for GO in case owned GO (fishing bobber case, for example)
        /// And permit out of range GO with no owner in case fishing hole
        if (!l_GameObject || (p_LootType != LOOT_FISHINGHOLE && (p_LootType != LOOT_FISHING || l_GameObject->GetOwnerGUID() != l_PlayerGuid)
            && !l_GameObject->IsWithinDistInMap(this, INTERACTION_DISTANCE)) || (p_LootType == LOOT_CORPSE && l_GameObject->GetRespawnTime() && l_GameObject->isSpawnedByDefault()))
        {
            SendLootRelease(p_Guid);
            return;
        }

        /// If gameobject is quest tracked and player already have it, player can't loot (cheat ?)
        uint32 l_TrackingQuest = l_GameObject->GetGOInfo()->GetTrackingQuestId();
        uint32 l_QuestBit      = GetQuestUniqueBitFlag(l_TrackingQuest);

        if (l_TrackingQuest && IsQuestBitFlaged(l_QuestBit))
        {
            SendLootRelease(p_Guid);
            return;
        }

        l_Loot = &l_GameObject->loot;

        if (l_GameObject->getLootState() == GO_READY)
        {
            uint32 l_LootID = l_GameObject->GetGOInfo()->GetLootId();

            /// TODO: fix this big hack
            if ((l_GameObject->GetEntry() == BG_AV_OBJECTID_MINE_N || l_GameObject->GetEntry() == BG_AV_OBJECTID_MINE_S))
            {
                if (Battleground* l_Battleground = GetBattleground())
                {
                    if (l_Battleground->GetTypeID(true) == BATTLEGROUND_AV)
                    {
                        if (!(((BattlegroundAV*)l_Battleground)->PlayerCanDoMineQuest(l_GameObject->GetEntry(), GetTeam())))
                        {
                            SendLootRelease(p_Guid);
                            return;
                        }
                    }
                }
            }

            if (l_LootID)
            {
                l_Loot->clear();

                Group* l_Group = GetGroup();
                bool l_GroupRules = (l_Group && l_GameObject->GetGOInfo()->type == GAMEOBJECT_TYPE_CHEST && l_GameObject->GetGOInfo()->chest.usegrouplootrules);

                /// Check current RR player and get next if necessary
                if (l_GroupRules)
                    l_Group->UpdateLooterGuid(l_GameObject, true);

                l_Loot->FillLoot(l_LootID, LootTemplates_Gameobject, this, !l_GroupRules, false, l_GameObject->GetLootMode());

                /// Get next RR player (for next loot)
                if (l_GroupRules)
                    l_Group->UpdateLooterGuid(l_GameObject);
            }

            if (p_LootType == LOOT_FISHING)
                l_GameObject->getFishLoot(l_Loot, this);

            if (l_GameObject->GetGOInfo()->type == GAMEOBJECT_TYPE_CHEST && l_GameObject->GetGOInfo()->chest.usegrouplootrules)
            {
                if (Group* l_Group = GetGroup())
                {
                    switch (l_Group->GetLootMethod())
                    {
                        case GROUP_LOOT:
                            /// GroupLoot: rolls items over threshold. Items with quality < threshold, round robin
                            l_Group->GroupLoot(l_Loot, l_GameObject);
                            break;
                        case NEED_BEFORE_GREED:
                            l_Group->NeedBeforeGreed(l_Loot, l_GameObject);
                            break;
                        case MASTER_LOOT:
                            l_Group->MasterLoot(l_Loot, l_GameObject);
                            break;
                        default:
                            break;
                    }
                }
            }

            l_GameObject->SetLootState(GO_ACTIVATED, this);
        }

        if (l_GameObject->getLootState() == GO_ACTIVATED)
        {
            if (Group* l_Group = GetGroup())
            {
                switch (l_Group->GetLootMethod())
                {
                    case MASTER_LOOT:
                        l_Permission = MASTER_PERMISSION;
                        break;
                    case FREE_FOR_ALL:
                        l_Permission = ALL_PERMISSION;
                        break;
                    case ROUND_ROBIN:
                        l_Permission = ROUND_ROBIN_PERMISSION;
                        break;
                    default:
                        l_Permission = GROUP_PERMISSION;
                        break;
                }
            }
            else
                l_Permission = ALL_PERMISSION;
        }
    }
    else if (IS_ITEM_GUID(p_Guid))
    {
        Item* l_Item = GetItemByGuid(p_Guid);
        if (!l_Item)
        {
            SendLootRelease(p_Guid);
            return;
        }

        l_Permission = OWNER_PERMISSION;

        l_Loot = &l_Item->loot;

        if (!l_Item->m_lootGenerated)
        {
            l_Item->m_lootGenerated = true;
            l_Loot->clear();

            switch (p_LootType)
            {
                case LOOT_DISENCHANTING:
                    l_Loot->FillLoot(l_Item->GetTemplate()->DisenchantID, LootTemplates_Disenchant, this, true);
                    break;
                case LOOT_PROSPECTING:
                    l_Loot->FillLoot(l_Item->GetEntry(), LootTemplates_Prospecting, this, true);
                    break;
                case LOOT_MILLING:
                    l_Loot->FillLoot(l_Item->GetEntry(), LootTemplates_Milling, this, true);
                    break;
                default:
                    l_Loot->generateMoneyLoot(l_Item->GetTemplate()->MinMoneyLoot, l_Item->GetTemplate()->MaxMoneyLoot);
                    l_Loot->FillLoot(l_Item->GetEntry(), LootTemplates_Item, this, true, l_Loot->Gold != 0);
                    break;
            }
        }
    }
    /// Remove insignia
    else if (IS_CORPSE_GUID(p_Guid))
    {
        Corpse* l_Corpse = ObjectAccessor::GetCorpse(*this, p_Guid);
        if (!l_Corpse || !(p_LootType == LOOT_CORPSE || p_LootType == LOOT_INSIGNIA) || l_Corpse->GetType() != CORPSE_BONES)
        {
            SendLootRelease(p_Guid);
            return;
        }

        l_Loot = &l_Corpse->loot;

        if (!l_Corpse->lootForBody)
        {
            l_Corpse->lootForBody = true;

            uint32 l_Gold = l_Corpse->loot.Gold;
            l_Corpse->loot.clear();

            if (Battleground* l_Battleground = GetBattleground())
            {
                if (l_Battleground->GetTypeID(true) == BATTLEGROUND_AV)
                    l_Loot->FillLoot(1, LootTemplates_Creature, this, true);
            }
            else if (OutdoorPvP* l_OutdoorPvP = sOutdoorPvPMgr->GetOutdoorPvPToZoneId(GetZoneId()))
            {
                if (l_OutdoorPvP->GetTypeId() == OutdoorPvPTypes::OUTDOOR_PVP_ASHRAN)
                    l_OutdoorPvP->FillCustomPvPLoots(this, *l_Loot, l_Corpse->GetOwnerGUID());
            }

            /// It may need a better formula
            /// Now it works like this: lvl10: ~6copper, lvl70: ~9silver
            l_Corpse->loot.Gold = uint32(urand(50, 150) * 0.016f * pow(float(l_Gold) / 5.76f, 2.5f) * sWorld->getRate(RATE_DROP_MONEY));
        }

        if (l_Corpse->lootRecipient != this)
            l_Permission = NONE_PERMISSION;
        else
            l_Permission = OWNER_PERMISSION;
    }
    else
    {
        Creature* l_Creature = GetMap()->GetCreature(p_Guid);

        /// Must be in range and creature must be alive for pickpocket and must be dead for another loot
        if (!l_Creature || l_Creature->isAlive() != (p_LootType == LOOT_PICKPOCKETING) || (!l_Creature->IsWithinDistInMap(this, INTERACTION_DISTANCE) && !p_FetchLoot))
        {
            SendLootRelease(p_Guid);
            return;
        }

        if (p_LootType == LOOT_PICKPOCKETING && IsFriendlyTo(l_Creature))
        {
            SendLootRelease(p_Guid);
            return;
        }

        l_Loot = &l_Creature->loot;
        l_Loot->LinkedLoot.clear();

        if (p_LootType == LOOT_PICKPOCKETING)
        {
            if (!l_Creature->lootForPickPocketed)
            {
                l_Creature->lootForPickPocketed = true;
                l_Loot->clear();

                if (uint32 l_LootID = l_Creature->GetCreatureTemplate()->pickpocketLootId)
                    l_Loot->FillLoot(l_LootID, LootTemplates_Pickpocketing, this, true);

                /// Generate extra money for pick pocket loot
                uint32 const l_A = urand(0, l_Creature->getLevel() / 2);
                uint32 const l_B = urand(0, getLevel() / 2);
                l_Loot->Gold = uint32(10 * (l_A + l_B) * sWorld->getRate(RATE_DROP_MONEY));
                l_Permission = OWNER_PERMISSION;
            }
        }
        else
        {
            /// Check all creature around, to see if we can loot it too
            std::list<Creature*> l_LinkedCreatures;
            l_LinkedCreatures.push_back(l_Creature);

            if (p_LootType == LOOT_CORPSE)
            {
                CellCoord l_CellCoord(JadeCore::ComputeCellCoord(GetPositionX(), GetPositionY()));
                Cell l_Cell(l_CellCoord);
                l_Cell.SetNoCreate();

                JadeCore::AllDeadCreaturesInRange l_Check(this, 25.0f, l_Creature->GetGUID());
                JadeCore::CreatureListSearcher<JadeCore::AllDeadCreaturesInRange> l_Searcher(this, l_LinkedCreatures, l_Check);
                TypeContainerVisitor<JadeCore::CreatureListSearcher<JadeCore::AllDeadCreaturesInRange>, GridTypeMapContainer> l_CellSearcher(l_Searcher);
                l_Cell.Visit(l_CellCoord, l_CellSearcher, *(GetMap()), *this, 25.0f);
            }

            uint32 l_MaxSlots = l_Loot->Items.size() + l_Loot->QuestItems.size();
            l_Loot->AdditionalLinkedGold = 0;
            for (Creature* l_LinkedCreature : l_LinkedCreatures)
            {
                /// The player whose group may loot the corpse
                Player* l_Recipient = l_LinkedCreature->GetLootRecipient();
                if (!l_Recipient)
                {
                    if (l_Creature != l_LinkedCreature)
                        continue;

                    return;
                }

                Loot* l_LinkedLoot = &l_LinkedCreature->loot;
                if (!l_LinkedCreature->lootForBody)
                {
                    l_LinkedCreature->lootForBody = true;

                    /// For creature, loot is filled when creature is killed.
                    if (Group* l_Group = l_Recipient->GetGroup())
                    {
                        switch (l_Group->GetLootMethod())
                        {
                            case GROUP_LOOT:
                                /// GroupLoot: rolls items over threshold. Items with quality < threshold, round robin
                                l_Group->GroupLoot(l_LinkedLoot, l_LinkedCreature);
                                break;
                            case NEED_BEFORE_GREED:
                                l_Group->NeedBeforeGreed(l_LinkedLoot, l_LinkedCreature);
                                break;
                            case MASTER_LOOT:
                                l_Group->MasterLoot(l_LinkedLoot, l_LinkedCreature);
                                break;
                            default:
                                break;
                        }
                    }
                }

                PermissionTypes l_Perm = NONE_PERMISSION;

                /// TODO: handle this case with new radius loot system
                /// Possible only if creature->lootForBody && loot->empty() at spell cast check
                if (p_LootType == LOOT_SKINNING)
                {
                    l_LinkedLoot->clear();
                    l_LinkedLoot->FillLoot(l_LinkedCreature->GetCreatureTemplate()->SkinLootId, LootTemplates_Skinning, this, true);
                    l_Perm = OWNER_PERMISSION;
                }
                /// Set group rights only for loot_type != LOOT_SKINNING
                else
                {
                    if (Group* l_Group = GetGroup())
                    {
                        if (l_Group == l_Recipient->GetGroup())
                        {
                            switch (l_Group->GetLootMethod())
                            {
                                case MASTER_LOOT:
                                    l_Perm = MASTER_PERMISSION;
                                    break;
                                case FREE_FOR_ALL:
                                    l_Perm = ALL_PERMISSION;
                                    break;
                                case ROUND_ROBIN:
                                    l_Perm = ROUND_ROBIN_PERMISSION;
                                    break;
                                default:
                                    l_Perm = GROUP_PERMISSION;
                                    break;
                            }
                        }
                        else
                            l_Perm = NONE_PERMISSION;
                    }
                    else if (l_Recipient == this)
                        l_Perm = OWNER_PERMISSION;
                    else
                        l_Perm = NONE_PERMISSION;
                }

                if (l_LinkedCreature == l_Creature)
                    l_Permission = l_Perm;
                else
                {
                    if (l_Perm != NONE_PERMISSION)
                    {
                        l_LinkedLoot->AddLooter(l_PlayerGuid);
                        l_Loot->AdditionalLinkedGold += l_LinkedLoot->Gold;
                    }

                    for (uint32 l_I = 0; l_I < l_LinkedLoot->Items.size(); l_I++)
                        l_Loot->addLinkedLoot(l_MaxSlots++, l_LinkedCreature->GetGUID(), l_I, l_Perm);
                }
            }
        }
    }

    SetLootGUID(p_Guid);

    /// LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
    switch (p_LootType)
    {
        case LOOT_INSIGNIA:
            p_LootType = LOOT_SKINNING;
            break;
        case LOOT_FISHINGHOLE:
            p_LootType = LOOT_FISHING;
            break;
        default:
            break;
    }

    /// In WoD, more you have fishing skill more the fish is bigger
    if (p_LootType == LOOT_FISHING || p_LootType == LOOT_FISHINGHOLE)
    {
        uint32 l_SmallFishChance    = 100;
        uint32 l_MediumFishChance   = 0;
        uint32 l_BigFishChance      = 0;

        uint32 l_FishingSKill = GetSkillValue(SKILL_FISHING);

        /// http://www.wowhead.com/achievement=9462/draenor-angler#comments
        if (l_FishingSKill >= 100 && l_FishingSKill < 525)
        {
            l_SmallFishChance  = 80;
            l_MediumFishChance = 20;
        }
        else if (l_FishingSKill >= 525 && l_FishingSKill < 700)
        {
            l_SmallFishChance   = 10;
            l_MediumFishChance  = 50;
            l_BigFishChance     = 10;
        }
        else if (l_FishingSKill >= 650 && l_FishingSKill < 700)
        {
            l_SmallFishChance   = 0;
            l_MediumFishChance  = 50;
            l_BigFishChance     = 50;
        }
        else if (l_FishingSKill >= 700)
        {
            l_SmallFishChance   = 0;
            l_BigFishChance     = std::min((int32)100, (int32)(50 + ((50 / (950 - 700)) * (l_FishingSKill - 700))));
            l_MediumFishChance  = std::max((int32)0, (int32)(100 - l_BigFishChance));
        }

        enum class FishType
        {
            None,
            Small,
            Medium,
            Big
        };

        /// Fish with various size :
        /// -------------------------------------------
        /// - Crescent Saberfish
        /// - Blackwater Whiptail
        /// - Abyssal Gulper Eel
        /// - Sea Scorpion
        /// - Fire Ammonite
        /// - Blind Lake Sturgeon
        /// - Fat Sleeper
        /// - Jawless Skulker
        /// - Savage Piranha
        std::vector<uint32> l_SmallFish  { 111589, 111650, 111651, 111652, 111656, 111658, 111659, 111662, 118564 };
        std::vector<uint32> l_MediumFish { 111595, 111663, 111664, 111665, 111666, 111667, 111668, 111669, 118565 };
        std::vector<uint32> l_BigFish    { 111601, 111670, 111671, 111672, 111673, 111674, 111675, 111676, 118566 };

        auto GetFishType = [l_SmallFish, l_MediumFish, l_BigFish](uint32 p_ItemID) -> FishType
        {
            if (std::find(l_SmallFish.begin(), l_SmallFish.end(), p_ItemID) != l_SmallFish.end())
                return FishType::Small;
            if (std::find(l_MediumFish.begin(), l_MediumFish.end(), p_ItemID) != l_MediumFish.end())
                return FishType::Medium;
            if (std::find(l_BigFish.begin(), l_BigFish.end(), p_ItemID) != l_BigFish.end())
                return FishType::Big;

            return FishType::None;
        };

        std::vector<LootItem*> l_Fishs;

        for (uint32 l_I = 0; l_I < l_Loot->Items.size(); ++l_I)
        {
            LootItem* l_LootItem = &l_Loot->Items[l_I];
            ItemTemplate const* l_ItemTemplate = sObjectMgr->GetItemTemplate(l_LootItem->itemid);

            if (!l_ItemTemplate)
                return;

            if (l_ItemTemplate->SubClass != ITEM_SUBCLASS_MEAT)
                continue;

            if (GetFishType(l_LootItem->itemid) == FishType::None)
                continue;

#ifdef _MSC_VER
            char* l_Size[] = { "None", "Small", "Medium", "Big" };
            ChatHandler(this).PSendSysMessage("Loot find fish %s(%u) size %s", l_ItemTemplate->Name1->Get(sWorld->GetDefaultDbcLocale()), l_LootItem->itemid, l_Size[(int)GetFishType(l_LootItem->itemid)]);
            ChatHandler(this).PSendSysMessage("Loot removed fish %s(%u)", l_ItemTemplate->Name1->Get(sWorld->GetDefaultDbcLocale()), l_LootItem->itemid);
#endif
            l_Fishs.push_back(l_LootItem);
            l_LootItem->needs_quest = true;
        }

        if (l_Fishs.size())
        {
            for (LootItem* l_LootItem : l_Fishs)
            {
                bool l_RoolResult = false;
                switch (GetFishType(l_LootItem->itemid))
                {
                    case FishType::Small:
                        l_RoolResult = roll_chance_i(l_SmallFishChance);
                        break;
                    case FishType::Medium:
                        l_RoolResult = roll_chance_i(l_MediumFishChance);
                        break;
                    case FishType::Big:
                        l_RoolResult = roll_chance_i(l_BigFishChance);
                        break;
                    default:
                        break;
                }

                if (l_RoolResult)
                {
#ifdef _MSC_VER
                    ItemTemplate const* l_ItemTemplate = sObjectMgr->GetItemTemplate(l_LootItem->itemid);
                    ChatHandler(this).PSendSysMessage("Loot added fish %s(%u)", l_ItemTemplate->Name1->Get(sWorld->GetDefaultDbcLocale()), l_LootItem->itemid);
#endif
                    l_LootItem->needs_quest = false;
                }
            }
        }
    }

    /// Need know merged fishing/corpse loot type for achievements
    l_Loot->Type = p_LootType;

    WorldPacket l_Data(SMSG_LOOT_RESPONSE, 4 * 1024);
    l_Data << LootView(*l_Loot, this, p_LootType, p_Guid, l_Permission);
    SendDirectMessage(&l_Data);

    /// Add 'this' player as one of the players that are looting 'loot'
    if (l_Permission != NONE_PERMISSION)
        l_Loot->AddLooter(l_PlayerGuid);

    if (p_LootType == LOOT_CORPSE && !IS_ITEM_GUID(p_Guid))
        SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
}

void Player::SendNotifyLootMoneyRemoved()
{
    ObjectGuid l_Guid = MAKE_NEW_GUID(GUID_LOPART(GetLootGUID()), 0, HIGHGUID_LOOT);

    sObjectMgr->setLootViewGUID(l_Guid, GetLootGUID());

    WorldPacket l_Data(SMSG_COIN_REMOVED);
    l_Data.appendPackGUID(l_Guid);
    GetSession()->SendPacket(&l_Data);
}

void Player::SendNotifyLootItemRemoved(uint8 p_LootSlot)
{
    ObjectGuid l_Guid       = GetLootGUID();
    ObjectGuid l_LootGuid   = MAKE_NEW_GUID(GUID_LOPART(l_Guid), 0, HIGHGUID_LOOT);

    WorldPacket l_Data(SMSG_LOOT_REMOVED);

    l_Data.appendPackGUID(l_Guid);
    l_Data.appendPackGUID(l_LootGuid);
    l_Data << uint8(p_LootSlot);

    GetSession()->SendPacket(&l_Data);
}

void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
{
    WorldPacket data(SMSG_UPDATE_WORLD_STATE, 4+4+1);
    data << Field;
    data << Value;
    data.WriteBit(0);
    data.FlushBits();
    GetSession()->SendPacket(&data);

    SetWorldState(Field, Value);
}

void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
{
    // data depends on zoneid/mapid...
    Battleground* bg = GetBattleground();
    uint16 NumberOfFields = 0; ///< NumberOfFields is unused
    uint32 mapid = GetMapId();
    OutdoorPvP* pvp = sOutdoorPvPMgr->GetOutdoorPvPToZoneId(zoneid);
    InstanceScript* instance = GetInstanceScript();

    sLog->outDebug(LOG_FILTER_NETWORKIO, "Sending SMSG_INIT_WORLD_STATES to Map: %u, Zone: %u", mapid, zoneid);

    ByteBuffer l_Buffer(10 * 1024);
    l_Buffer << uint32(0x8d8) << uint32(0x0);                   // 1
    l_Buffer << uint32(0x8d7) << uint32(0x0);                   // 2
    l_Buffer << uint32(0x8d6) << uint32(0x0);                   // 3
    l_Buffer << uint32(0x8d5) << uint32(0x0);                   // 4
    l_Buffer << uint32(0x8d4) << uint32(0x0);                   // 5
    l_Buffer << uint32(0x8d3) << uint32(0x0);                   // 6

    if (mapid == 530)                                       // Outland
    {
        l_Buffer << uint32(0x9bf) << uint32(0x0);               // 7
        l_Buffer << uint32(0x9bd) << uint32(0xF);               // 8
        l_Buffer << uint32(0x9bb) << uint32(0xF);               // 9
    }

    // insert <field> <value>
    switch (zoneid)
    {
        case 1:                                             // Dun Morogh
        case 11:                                            // Wetlands
        case 12:                                            // Elwynn Forest
        case 38:                                            // Loch Modan
        case 40:                                            // Westfall
        case 51:                                            // Searing Gorge
        case 1519:                                          // Stormwind City
        case 1537:                                          // Ironforge
        case 2257:                                          // Deeprun Tram
        case 3703:                                          // Shattrath City
            break;
        case 1377:                                          // Silithus
            if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_SI)
                pvp->FillInitialWorldStates(l_Buffer);
            else
            {
                // states are always shown
                l_Buffer << uint32(2313) << uint32(0x0); // 7 ally silityst gathered
                l_Buffer << uint32(2314) << uint32(0x0); // 8 horde silityst gathered
                l_Buffer << uint32(2317) << uint32(0x0); // 9 max silithyst
            }
            // dunno about these... aq opening event maybe?
            l_Buffer << uint32(2322) << uint32(0x0); // 10 sandworm N
            l_Buffer << uint32(2323) << uint32(0x0); // 11 sandworm S
            l_Buffer << uint32(2324) << uint32(0x0); // 12 sandworm SW
            l_Buffer << uint32(2325) << uint32(0x0); // 13 sandworm E
            break;
        case 2597:                                          // Alterac Valley
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_AV)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0x7ae) << uint32(0x1);           // 7 snowfall n
                l_Buffer << uint32(0x532) << uint32(0x1);           // 8 frostwolfhut hc
                l_Buffer << uint32(0x531) << uint32(0x0);           // 9 frostwolfhut ac
                l_Buffer << uint32(0x52e) << uint32(0x0);           // 10 stormpike firstaid a_a
                l_Buffer << uint32(0x571) << uint32(0x0);           // 11 east frostwolf tower horde assaulted -unused
                l_Buffer << uint32(0x570) << uint32(0x0);           // 12 west frostwolf tower horde assaulted - unused
                l_Buffer << uint32(0x567) << uint32(0x1);           // 13 frostwolfe c
                l_Buffer << uint32(0x566) << uint32(0x1);           // 14 frostwolfw c
                l_Buffer << uint32(0x550) << uint32(0x1);           // 15 irondeep (N) ally
                l_Buffer << uint32(0x544) << uint32(0x0);           // 16 ice grave a_a
                l_Buffer << uint32(0x536) << uint32(0x0);           // 17 stormpike grave h_c
                l_Buffer << uint32(0x535) << uint32(0x1);           // 18 stormpike grave a_c
                l_Buffer << uint32(0x518) << uint32(0x0);           // 19 stoneheart grave a_a
                l_Buffer << uint32(0x517) << uint32(0x0);           // 20 stoneheart grave h_a
                l_Buffer << uint32(0x574) << uint32(0x0);           // 21 1396 unk
                l_Buffer << uint32(0x573) << uint32(0x0);           // 22 iceblood tower horde assaulted -unused
                l_Buffer << uint32(0x572) << uint32(0x0);           // 23 towerpoint horde assaulted - unused
                l_Buffer << uint32(0x56f) << uint32(0x0);           // 24 1391 unk
                l_Buffer << uint32(0x56e) << uint32(0x0);           // 25 iceblood a
                l_Buffer << uint32(0x56d) << uint32(0x0);           // 26 towerp a
                l_Buffer << uint32(0x56c) << uint32(0x0);           // 27 frostwolfe a
                l_Buffer << uint32(0x56b) << uint32(0x0);           // 28 froswolfw a
                l_Buffer << uint32(0x56a) << uint32(0x1);           // 29 1386 unk
                l_Buffer << uint32(0x569) << uint32(0x1);           // 30 iceblood c
                l_Buffer << uint32(0x568) << uint32(0x1);           // 31 towerp c
                l_Buffer << uint32(0x565) << uint32(0x0);           // 32 stoneh tower a
                l_Buffer << uint32(0x564) << uint32(0x0);           // 33 icewing tower a
                l_Buffer << uint32(0x563) << uint32(0x0);           // 34 dunn a
                l_Buffer << uint32(0x562) << uint32(0x0);           // 35 duns a
                l_Buffer << uint32(0x561) << uint32(0x0);           // 36 stoneheart bunker alliance assaulted - unused
                l_Buffer << uint32(0x560) << uint32(0x0);           // 37 icewing bunker alliance assaulted - unused
                l_Buffer << uint32(0x55f) << uint32(0x0);           // 38 dunbaldar south alliance assaulted - unused
                l_Buffer << uint32(0x55e) << uint32(0x0);           // 39 dunbaldar north alliance assaulted - unused
                l_Buffer << uint32(0x55d) << uint32(0x0);           // 40 stone tower d
                l_Buffer << uint32(0x3c6) << uint32(0x0);           // 41 966 unk
                l_Buffer << uint32(0x3c4) << uint32(0x0);           // 42 964 unk
                l_Buffer << uint32(0x3c2) << uint32(0x0);           // 43 962 unk
                l_Buffer << uint32(0x516) << uint32(0x1);           // 44 stoneheart grave a_c
                l_Buffer << uint32(0x515) << uint32(0x0);           // 45 stonheart grave h_c
                l_Buffer << uint32(0x3b6) << uint32(0x0);           // 46 950 unk
                l_Buffer << uint32(0x55c) << uint32(0x0);           // 47 icewing tower d
                l_Buffer << uint32(0x55b) << uint32(0x0);           // 48 dunn d
                l_Buffer << uint32(0x55a) << uint32(0x0);           // 49 duns d
                l_Buffer << uint32(0x559) << uint32(0x0);           // 50 1369 unk
                l_Buffer << uint32(0x558) << uint32(0x0);           // 51 iceblood d
                l_Buffer << uint32(0x557) << uint32(0x0);           // 52 towerp d
                l_Buffer << uint32(0x556) << uint32(0x0);           // 53 frostwolfe d
                l_Buffer << uint32(0x555) << uint32(0x0);           // 54 frostwolfw d
                l_Buffer << uint32(0x554) << uint32(0x1);           // 55 stoneh tower c
                l_Buffer << uint32(0x553) << uint32(0x1);           // 56 icewing tower c
                l_Buffer << uint32(0x552) << uint32(0x1);           // 57 dunn c
                l_Buffer << uint32(0x551) << uint32(0x1);           // 58 duns c
                l_Buffer << uint32(0x54f) << uint32(0x0);           // 59 irondeep (N) horde
                l_Buffer << uint32(0x54e) << uint32(0x0);           // 60 irondeep (N) ally
                l_Buffer << uint32(0x54d) << uint32(0x1);           // 61 mine (S) neutral
                l_Buffer << uint32(0x54c) << uint32(0x0);           // 62 mine (S) horde
                l_Buffer << uint32(0x54b) << uint32(0x0);           // 63 mine (S) ally
                l_Buffer << uint32(0x545) << uint32(0x0);           // 64 iceblood h_a
                l_Buffer << uint32(0x543) << uint32(0x1);           // 65 iceblod h_c
                l_Buffer << uint32(0x542) << uint32(0x0);           // 66 iceblood a_c
                l_Buffer << uint32(0x540) << uint32(0x0);           // 67 snowfall h_a
                l_Buffer << uint32(0x53f) << uint32(0x0);           // 68 snowfall a_a
                l_Buffer << uint32(0x53e) << uint32(0x0);           // 69 snowfall h_c
                l_Buffer << uint32(0x53d) << uint32(0x0);           // 70 snowfall a_c
                l_Buffer << uint32(0x53c) << uint32(0x0);           // 71 frostwolf g h_a
                l_Buffer << uint32(0x53b) << uint32(0x0);           // 72 frostwolf g a_a
                l_Buffer << uint32(0x53a) << uint32(0x1);           // 73 frostwolf g h_c
                l_Buffer << uint32(0x539) << uint32(0x0);           // 74 frostwolf g a_c
                l_Buffer << uint32(0x538) << uint32(0x0);           // 75 stormpike grave h_a
                l_Buffer << uint32(0x537) << uint32(0x0);           // 76 stormpike grave a_a
                l_Buffer << uint32(0x534) << uint32(0x0);           // 77 frostwolf hut h_a
                l_Buffer << uint32(0x533) << uint32(0x0);           // 78 frostwolf hut a_a
                l_Buffer << uint32(0x530) << uint32(0x0);           // 79 stormpike first aid h_a
                l_Buffer << uint32(0x52f) << uint32(0x0);           // 80 stormpike first aid h_c
                l_Buffer << uint32(0x52d) << uint32(0x1);           // 81 stormpike first aid a_c
            }
            break;
        case 3277:                                          // Warsong Gulch
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_WS)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0x62d) << uint32(0x0);       // 7 1581 alliance flag captures
                l_Buffer << uint32(0x62e) << uint32(0x0);       // 8 1582 horde flag captures
                l_Buffer << uint32(0x609) << uint32(0x0);       // 9 1545 unk, set to 1 on alliance flag pickup...
                l_Buffer << uint32(0x60a) << uint32(0x0);       // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
                l_Buffer << uint32(0x60b) << uint32(0x2);       // 11 1547 unk
                l_Buffer << uint32(0x641) << uint32(0x3);       // 12 1601 unk (max flag captures?)
                l_Buffer << uint32(0x922) << uint32(0x1);       // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
                l_Buffer << uint32(0x923) << uint32(0x1);       // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
            }
            break;
        case 3358:                                          // Arathi Basin
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_AB)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0x6e7) << uint32(0x0);       // 7 1767 stables alliance
                l_Buffer << uint32(0x6e8) << uint32(0x0);       // 8 1768 stables horde
                l_Buffer << uint32(0x6e9) << uint32(0x0);       // 9 1769 unk, ST?
                l_Buffer << uint32(0x6ea) << uint32(0x0);       // 10 1770 stables (show/hide)
                l_Buffer << uint32(0x6ec) << uint32(0x0);       // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
                l_Buffer << uint32(0x6ed) << uint32(0x0);       // 12 1773 farm (show/hide)
                l_Buffer << uint32(0x6ee) << uint32(0x0);       // 13 1774 farm color
                l_Buffer << uint32(0x6ef) << uint32(0x0);       // 14 1775 gold mine color, may be FM?
                l_Buffer << uint32(0x6f0) << uint32(0x0);       // 15 1776 alliance resources
                l_Buffer << uint32(0x6f1) << uint32(0x0);       // 16 1777 horde resources
                l_Buffer << uint32(0x6f2) << uint32(0x0);       // 17 1778 horde bases
                l_Buffer << uint32(0x6f3) << uint32(0x0);       // 18 1779 alliance bases
                l_Buffer << uint32(0x6f4) << uint32(0x7d0);     // 19 1780 max resources (2000)
                l_Buffer << uint32(0x6f6) << uint32(0x0);       // 20 1782 blacksmith color
                l_Buffer << uint32(0x6f7) << uint32(0x0);       // 21 1783 blacksmith (show/hide)
                l_Buffer << uint32(0x6f8) << uint32(0x0);       // 22 1784 unk, bs?
                l_Buffer << uint32(0x6f9) << uint32(0x0);       // 23 1785 unk, bs?
                l_Buffer << uint32(0x6fb) << uint32(0x0);       // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
                l_Buffer << uint32(0x6fc) << uint32(0x0);       // 25 1788 gold mine (0 - conflict, 1 - horde)
                l_Buffer << uint32(0x6fd) << uint32(0x0);       // 26 1789 gold mine (1 - show/0 - hide)
                l_Buffer << uint32(0x6fe) << uint32(0x0);       // 27 1790 gold mine color
                l_Buffer << uint32(0x700) << uint32(0x0);       // 28 1792 gold mine color, wtf?, may be LM?
                l_Buffer << uint32(0x701) << uint32(0x0);       // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
                l_Buffer << uint32(0x702) << uint32(0x0);       // 30 1794 lumber mill (show/hide)
                l_Buffer << uint32(0x703) << uint32(0x0);       // 31 1795 lumber mill color color
                l_Buffer << uint32(0x732) << uint32(0x1);       // 32 1842 stables (1 - uncontrolled)
                l_Buffer << uint32(0x733) << uint32(0x1);       // 33 1843 gold mine (1 - uncontrolled)
                l_Buffer << uint32(0x734) << uint32(0x1);       // 34 1844 lumber mill (1 - uncontrolled)
                l_Buffer << uint32(0x735) << uint32(0x1);       // 35 1845 farm (1 - uncontrolled)
                l_Buffer << uint32(0x736) << uint32(0x1);       // 36 1846 blacksmith (1 - uncontrolled)
                l_Buffer << uint32(0x745) << uint32(0x2);       // 37 1861 unk
                l_Buffer << uint32(0x7a3) << uint32(0x708);     // 38 1955 warning limit (1800)
            }
            break;
        case 3820:                                          // Eye of the Storm
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_EY)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0xac1) << uint32(0x0);       // 7  2753 Horde Bases
                l_Buffer << uint32(0xac0) << uint32(0x0);       // 8  2752 Alliance Bases
                l_Buffer << uint32(0xab6) << uint32(0x0);       // 9  2742 Mage Tower - Horde conflict
                l_Buffer << uint32(0xab5) << uint32(0x0);       // 10 2741 Mage Tower - Alliance conflict
                l_Buffer << uint32(0xab4) << uint32(0x0);       // 11 2740 Fel Reaver - Horde conflict
                l_Buffer << uint32(0xab3) << uint32(0x0);       // 12 2739 Fel Reaver - Alliance conflict
                l_Buffer << uint32(0xab2) << uint32(0x0);       // 13 2738 Draenei - Alliance conflict
                l_Buffer << uint32(0xab1) << uint32(0x0);       // 14 2737 Draenei - Horde conflict
                l_Buffer << uint32(0xab0) << uint32(0x0);       // 15 2736 unk // 0 at start
                l_Buffer << uint32(0xaaf) << uint32(0x0);       // 16 2735 unk // 0 at start
                l_Buffer << uint32(0xaad) << uint32(0x0);       // 17 2733 Draenei - Horde control
                l_Buffer << uint32(0xaac) << uint32(0x0);       // 18 2732 Draenei - Alliance control
                l_Buffer << uint32(0xaab) << uint32(0x1);       // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
                l_Buffer << uint32(0xaaa) << uint32(0x0);       // 20 2730 Mage Tower - Alliance control
                l_Buffer << uint32(0xaa9) << uint32(0x0);       // 21 2729 Mage Tower - Horde control
                l_Buffer << uint32(0xaa8) << uint32(0x1);       // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
                l_Buffer << uint32(0xaa7) << uint32(0x0);       // 23 2727 Fel Reaver - Horde control
                l_Buffer << uint32(0xaa6) << uint32(0x0);       // 24 2726 Fel Reaver - Alliance control
                l_Buffer << uint32(0xaa5) << uint32(0x1);       // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
                l_Buffer << uint32(0xaa4) << uint32(0x0);       // 26 2724 Boold Elf - Horde control
                l_Buffer << uint32(0xaa3) << uint32(0x0);       // 27 2723 Boold Elf - Alliance control
                l_Buffer << uint32(0xaa2) << uint32(0x1);       // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
                l_Buffer << uint32(0xac5) << uint32(0x1);       // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
                l_Buffer << uint32(0xad2) << uint32(0x1);       // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
                l_Buffer << uint32(0xad1) << uint32(0x1);       // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
                l_Buffer << uint32(0xabe) << uint32(0x0);       // 32 2750 Horde resources
                l_Buffer << uint32(0xabd) << uint32(0x0);       // 33 2749 Alliance resources
                l_Buffer << uint32(0xa05) << uint32(0x8e);      // 34 2565 unk, constant?
                l_Buffer << uint32(0xaa0) << uint32(0x0);       // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
                l_Buffer << uint32(0xa9f) << uint32(0x0);       // 36 2719 Capturing progress-bar (0 - left, 100 - right)
                l_Buffer << uint32(0xa9e) << uint32(0x0);       // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
                l_Buffer << uint32(0xc0d) << uint32(0x17b);     // 38 3085 unk
                // and some more ... unknown
            }
            break;
        // any of these needs change! the client remembers the prev setting!
        // ON EVERY ZONE LEAVE, RESET THE OLD ZONE'S WORLD STATE, BUT AT LEAST THE UI STUFF!
        case 3483:                                          // Hellfire Peninsula
            if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_HP)
                pvp->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0x9ba) << uint32(0x1);           // 10 // add ally tower main gui icon       // maybe should be sent only on login?
                l_Buffer << uint32(0x9b9) << uint32(0x1);           // 11 // add horde tower main gui icon      // maybe should be sent only on login?
                l_Buffer << uint32(0x9b5) << uint32(0x0);           // 12 // show neutral broken hill icon      // 2485
                l_Buffer << uint32(0x9b4) << uint32(0x1);           // 13 // show icon above broken hill        // 2484
                l_Buffer << uint32(0x9b3) << uint32(0x0);           // 14 // show ally broken hill icon         // 2483
                l_Buffer << uint32(0x9b2) << uint32(0x0);           // 15 // show neutral overlook icon         // 2482
                l_Buffer << uint32(0x9b1) << uint32(0x1);           // 16 // show the overlook arrow            // 2481
                l_Buffer << uint32(0x9b0) << uint32(0x0);           // 17 // show ally overlook icon            // 2480
                l_Buffer << uint32(0x9ae) << uint32(0x0);           // 18 // horde pvp objectives captured      // 2478
                l_Buffer << uint32(0x9ac) << uint32(0x0);           // 19 // ally pvp objectives captured       // 2476
                l_Buffer << uint32(2475)  << uint32(100); //: ally / horde slider grey area                              // show only in direct vicinity!
                l_Buffer << uint32(2474)  << uint32(50);  //: ally / horde slider percentage, 100 for ally, 0 for horde  // show only in direct vicinity!
                l_Buffer << uint32(2473)  << uint32(0);   //: ally / horde slider display                                // show only in direct vicinity!
                l_Buffer << uint32(0x9a8) << uint32(0x0);           // 20 // show the neutral stadium icon      // 2472
                l_Buffer << uint32(0x9a7) << uint32(0x0);           // 21 // show the ally stadium icon         // 2471
                l_Buffer << uint32(0x9a6) << uint32(0x1);           // 22 // show the horde stadium icon        // 2470
            }
            break;
        case 3518:                                          // Nagrand
            if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_NA)
                pvp->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(2503) << uint32(0x0);    // 10
                l_Buffer << uint32(2502) << uint32(0x0);    // 11
                l_Buffer << uint32(2493) << uint32(0x0);    // 12
                l_Buffer << uint32(2491) << uint32(0x0);    // 13

                l_Buffer << uint32(2495) << uint32(0x0);    // 14
                l_Buffer << uint32(2494) << uint32(0x0);    // 15
                l_Buffer << uint32(2497) << uint32(0x0);    // 16

                l_Buffer << uint32(2762) << uint32(0x0);    // 17
                l_Buffer << uint32(2662) << uint32(0x0);    // 18
                l_Buffer << uint32(2663) << uint32(0x0);    // 19
                l_Buffer << uint32(2664) << uint32(0x0);    // 20

                l_Buffer << uint32(2760) << uint32(0x0);    // 21
                l_Buffer << uint32(2670) << uint32(0x0);    // 22
                l_Buffer << uint32(2668) << uint32(0x0);    // 23
                l_Buffer << uint32(2669) << uint32(0x0);    // 24

                l_Buffer << uint32(2761) << uint32(0x0);    // 25
                l_Buffer << uint32(2667) << uint32(0x0);    // 26
                l_Buffer << uint32(2665) << uint32(0x0);    // 27
                l_Buffer << uint32(2666) << uint32(0x0);    // 28

                l_Buffer << uint32(2763) << uint32(0x0);    // 29
                l_Buffer << uint32(2659) << uint32(0x0);    // 30
                l_Buffer << uint32(2660) << uint32(0x0);    // 31
                l_Buffer << uint32(2661) << uint32(0x0);    // 32

                l_Buffer << uint32(2671) << uint32(0x0);    // 33
                l_Buffer << uint32(2676) << uint32(0x0);    // 34
                l_Buffer << uint32(2677) << uint32(0x0);    // 35
                l_Buffer << uint32(2672) << uint32(0x0);    // 36
                l_Buffer << uint32(2673) << uint32(0x0);    // 37
            }
            break;
        case 3519:                                          // Terokkar Forest
            if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_TF)
                pvp->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0xa41) << uint32(0x0);           // 10 // 2625 capture bar pos
                l_Buffer << uint32(0xa40) << uint32(0x14);          // 11 // 2624 capture bar neutral
                l_Buffer << uint32(0xa3f) << uint32(0x0);           // 12 // 2623 show capture bar
                l_Buffer << uint32(0xa3e) << uint32(0x0);           // 13 // 2622 horde towers controlled
                l_Buffer << uint32(0xa3d) << uint32(0x5);           // 14 // 2621 ally towers controlled
                l_Buffer << uint32(0xa3c) << uint32(0x0);           // 15 // 2620 show towers controlled
                l_Buffer << uint32(0xa88) << uint32(0x0);           // 16 // 2696 SE Neu
                l_Buffer << uint32(0xa87) << uint32(0x0);           // 17 // SE Horde
                l_Buffer << uint32(0xa86) << uint32(0x0);           // 18 // SE Ally
                l_Buffer << uint32(0xa85) << uint32(0x0);           // 19 //S Neu
                l_Buffer << uint32(0xa84) << uint32(0x0);           // 20 S Horde
                l_Buffer << uint32(0xa83) << uint32(0x0);           // 21 S Ally
                l_Buffer << uint32(0xa82) << uint32(0x0);           // 22 NE Neu
                l_Buffer << uint32(0xa81) << uint32(0x0);           // 23 NE Horde
                l_Buffer << uint32(0xa80) << uint32(0x0);           // 24 NE Ally
                l_Buffer << uint32(0xa7e) << uint32(0x0);           // 25 // 2686 N Neu
                l_Buffer << uint32(0xa7d) << uint32(0x0);           // 26 N Horde
                l_Buffer << uint32(0xa7c) << uint32(0x0);           // 27 N Ally
                l_Buffer << uint32(0xa7b) << uint32(0x0);           // 28 NW Ally
                l_Buffer << uint32(0xa7a) << uint32(0x0);           // 29 NW Horde
                l_Buffer << uint32(0xa79) << uint32(0x0);           // 30 NW Neutral
                l_Buffer << uint32(0x9d0) << uint32(0x5);           // 31 // 2512 locked time remaining seconds first digit
                l_Buffer << uint32(0x9ce) << uint32(0x0);           // 32 // 2510 locked time remaining seconds second digit
                l_Buffer << uint32(0x9cd) << uint32(0x0);           // 33 // 2509 locked time remaining minutes
                l_Buffer << uint32(0x9cc) << uint32(0x0);           // 34 // 2508 neutral locked time show
                l_Buffer << uint32(0xad0) << uint32(0x0);           // 35 // 2768 horde locked time show
                l_Buffer << uint32(0xacf) << uint32(0x1);           // 36 // 2767 ally locked time show
            }
            break;
        case 3521:                                          // Zangarmarsh
            if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_ZM)
                pvp->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0x9e1) << uint32(0x0);           // 10 //2529
                l_Buffer << uint32(0x9e0) << uint32(0x0);           // 11
                l_Buffer << uint32(0x9df) << uint32(0x0);           // 12
                l_Buffer << uint32(0xa5d) << uint32(0x1);           // 13 //2653
                l_Buffer << uint32(0xa5c) << uint32(0x0);           // 14 //2652 east beacon neutral
                l_Buffer << uint32(0xa5b) << uint32(0x1);           // 15 horde
                l_Buffer << uint32(0xa5a) << uint32(0x0);           // 16 ally
                l_Buffer << uint32(0xa59) << uint32(0x1);           // 17 // 2649 Twin spire graveyard horde  12???
                l_Buffer << uint32(0xa58) << uint32(0x0);           // 18 ally     14 ???
                l_Buffer << uint32(0xa57) << uint32(0x0);           // 19 neutral  7???
                l_Buffer << uint32(0xa56) << uint32(0x0);           // 20 // 2646 west beacon neutral
                l_Buffer << uint32(0xa55) << uint32(0x1);           // 21 horde
                l_Buffer << uint32(0xa54) << uint32(0x0);           // 22 ally
                l_Buffer << uint32(0x9e7) << uint32(0x0);           // 23 // 2535
                l_Buffer << uint32(0x9e6) << uint32(0x0);           // 24
                l_Buffer << uint32(0x9e5) << uint32(0x0);           // 25
                l_Buffer << uint32(0xa00) << uint32(0x0);           // 26 // 2560
                l_Buffer << uint32(0x9ff) << uint32(0x1);           // 27
                l_Buffer << uint32(0x9fe) << uint32(0x0);           // 28
                l_Buffer << uint32(0x9fd) << uint32(0x0);           // 29
                l_Buffer << uint32(0x9fc) << uint32(0x1);           // 30
                l_Buffer << uint32(0x9fb) << uint32(0x0);           // 31
                l_Buffer << uint32(0xa62) << uint32(0x0);           // 32 // 2658
                l_Buffer << uint32(0xa61) << uint32(0x1);           // 33
                l_Buffer << uint32(0xa60) << uint32(0x1);           // 34
                l_Buffer << uint32(0xa5f) << uint32(0x0);           // 35
            }
            break;
        case 3698:                                          // Nagrand Arena
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_NA)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0xa0f) << uint32(0x0);           // 7
                l_Buffer << uint32(0xa10) << uint32(0x0);           // 8
                l_Buffer << uint32(0xa11) << uint32(0x0);           // 9 show
            }
            break;
        case 3702:                                          // Blade's Edge Arena
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_BE)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0x9f0) << uint32(0x0);           // 7 gold
                l_Buffer << uint32(0x9f1) << uint32(0x0);           // 8 green
                l_Buffer << uint32(0x9f3) << uint32(0x0);           // 9 show
            }
            break;
        case 3968:                                          // Ruins of Lordaeron
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_RL)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0xbb8) << uint32(0x0);           // 7 gold
                l_Buffer << uint32(0xbb9) << uint32(0x0);           // 8 green
                l_Buffer << uint32(0xbba) << uint32(0x0);           // 9 show
            }
            break;
        case 4378:                                          // Dalaran Sewers
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_DS)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(3601) << uint32(0x0);           // 7 gold
                l_Buffer << uint32(3600) << uint32(0x0);           // 8 green
                l_Buffer << uint32(3610) << uint32(0x0);           // 9 show
            }
            break;
        case 4384:                                          // Strand of the Ancients
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_SA)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                // 1-3 A defend, 4-6 H defend, 7-9 unk defend, 1 - ok, 2 - half destroyed, 3 - destroyed
                l_Buffer << uint32(0xf09) << uint32(0x0);       // 7  3849 Gate of Temple
                l_Buffer << uint32(0xe36) << uint32(0x0);       // 8  3638 Gate of Yellow Moon
                l_Buffer << uint32(0xe27) << uint32(0x0);       // 9  3623 Gate of Green Emerald
                l_Buffer << uint32(0xe24) << uint32(0x0);       // 10 3620 Gate of Blue Sapphire
                l_Buffer << uint32(0xe21) << uint32(0x0);       // 11 3617 Gate of Red Sun
                l_Buffer << uint32(0xe1e) << uint32(0x0);       // 12 3614 Gate of Purple Ametyst

                l_Buffer << uint32(0xdf3) << uint32(0x0);       // 13 3571 bonus timer (1 - on, 0 - off)
                l_Buffer << uint32(0xded) << uint32(0x0);       // 14 3565 Horde Attacker
                l_Buffer << uint32(0xdec) << uint32(0x0);       // 15 3564 Alliance Attacker
                // End Round (timer), better explain this by example, eg. ends in 19:59 -> A:BC
                l_Buffer << uint32(0xde9) << uint32(0x0);       // 16 3561 C
                l_Buffer << uint32(0xde8) << uint32(0x0);       // 17 3560 B
                l_Buffer << uint32(0xde7) << uint32(0x0);       // 18 3559 A
                l_Buffer << uint32(0xe35) << uint32(0x0);       // 19 3637 East g - Horde control
                l_Buffer << uint32(0xe34) << uint32(0x0);       // 20 3636 West g - Horde control
                l_Buffer << uint32(0xe33) << uint32(0x0);       // 21 3635 South g - Horde control
                l_Buffer << uint32(0xe32) << uint32(0x0);       // 22 3634 East g - Alliance control
                l_Buffer << uint32(0xe31) << uint32(0x0);       // 23 3633 West g - Alliance control
                l_Buffer << uint32(0xe30) << uint32(0x0);       // 24 3632 South g - Alliance control
                l_Buffer << uint32(0xe2f) << uint32(0x0);       // 25 3631 Chamber of Ancients - Horde control
                l_Buffer << uint32(0xe2e) << uint32(0x0);       // 26 3630 Chamber of Ancients - Alliance control
                l_Buffer << uint32(0xe2d) << uint32(0x0);       // 27 3629 Beach1 - Horde control
                l_Buffer << uint32(0xe2c) << uint32(0x0);       // 28 3628 Beach2 - Horde control
                l_Buffer << uint32(0xe2b) << uint32(0x0);       // 29 3627 Beach1 - Alliance control
                l_Buffer << uint32(0xe2a) << uint32(0x0);       // 30 3626 Beach2 - Alliance control
                // and many unks...
            }
            break;
        case 4406:                                          // Ring of Valor
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_RV)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0xe10) << uint32(0x0);           // 7 gold
                l_Buffer << uint32(0xe11) << uint32(0x0);           // 8 green
                l_Buffer << uint32(0xe1a) << uint32(0x0);           // 9 show
            }
            break;
        case 4710:
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_IC)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(4221) << uint32(1); // 7 BG_IC_ALLIANCE_RENFORT_SET
                l_Buffer << uint32(4222) << uint32(1); // 8 BG_IC_HORDE_RENFORT_SET
                l_Buffer << uint32(4226) << uint32(300); // 9 BG_IC_ALLIANCE_RENFORT
                l_Buffer << uint32(4227) << uint32(300); // 10 BG_IC_HORDE_RENFORT
                l_Buffer << uint32(4322) << uint32(1); // 11 BG_IC_GATE_FRONT_H_WS_OPEN
                l_Buffer << uint32(4321) << uint32(1); // 12 BG_IC_GATE_WEST_H_WS_OPEN
                l_Buffer << uint32(4320) << uint32(1); // 13 BG_IC_GATE_EAST_H_WS_OPEN
                l_Buffer << uint32(4323) << uint32(1); // 14 BG_IC_GATE_FRONT_A_WS_OPEN
                l_Buffer << uint32(4324) << uint32(1); // 15 BG_IC_GATE_WEST_A_WS_OPEN
                l_Buffer << uint32(4325) << uint32(1); // 16 BG_IC_GATE_EAST_A_WS_OPEN
                l_Buffer << uint32(4317) << uint32(1); // 17 unknown

                l_Buffer << uint32(4301) << uint32(1); // 18 BG_IC_DOCKS_UNCONTROLLED
                l_Buffer << uint32(4296) << uint32(1); // 19 BG_IC_HANGAR_UNCONTROLLED
                l_Buffer << uint32(4306) << uint32(1); // 20 BG_IC_QUARRY_UNCONTROLLED
                l_Buffer << uint32(4311) << uint32(1); // 21 BG_IC_REFINERY_UNCONTROLLED
                l_Buffer << uint32(4294) << uint32(1); // 22 BG_IC_WORKSHOP_UNCONTROLLED
                l_Buffer << uint32(4243) << uint32(1); // 23 unknown
                l_Buffer << uint32(4345) << uint32(1); // 24 unknown
            }
            break;
        // The Ruby Sanctum
        case 4987:
            if (instance && mapid == 724)
                instance->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(5049) << uint32(50);             // 9 WORLDSTATE_CORPOREALITY_MATERIAL
                l_Buffer << uint32(5050) << uint32(50);             // 10 WORLDSTATE_CORPOREALITY_TWILIGHT
                l_Buffer << uint32(5051) << uint32(0);              // 11 WORLDSTATE_CORPOREALITY_TOGGLE
            }
            break;
        // Icecrown Citadel
        case 4812:
            if (instance && mapid == 631)
                instance->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(4903) << uint32(0);              // 9  WORLDSTATE_SHOW_TIMER (Blood Quickening weekly)
                l_Buffer << uint32(4904) << uint32(30);             // 10 WORLDSTATE_EXECUTION_TIME
                l_Buffer << uint32(4940) << uint32(0);              // 11 WORLDSTATE_SHOW_ATTEMPTS
                l_Buffer << uint32(4941) << uint32(50);             // 12 WORLDSTATE_ATTEMPTS_REMAINING
                l_Buffer << uint32(4942) << uint32(50);             // 13 WORLDSTATE_ATTEMPTS_MAX
            }
            break;
        // The Culling of Stratholme
        case 4100:
            if (instance && mapid == 595)
                instance->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(3479) << uint32(0);              // 9  WORLDSTATE_SHOW_CRATES
                l_Buffer << uint32(3480) << uint32(0);              // 10 WORLDSTATE_CRATES_REVEALED
                l_Buffer << uint32(3504) << uint32(0);              // 11 WORLDSTATE_WAVE_COUNT
                l_Buffer << uint32(3931) << uint32(25);             // 12 WORLDSTATE_TIME_GUARDIAN
                l_Buffer << uint32(3932) << uint32(0);              // 13 WORLDSTATE_TIME_GUARDIAN_SHOW
            }
            break;
        // The Oculus
        case 4228:
            if (instance && mapid == 578)
                instance->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(3524) << uint32(0); // 9 WORLD_STATE_CENTRIFUGE_CONSTRUCT_SHOW
                l_Buffer << uint32(3486) << uint32(0); // 10 WORLD_STATE_CENTRIFUGE_CONSTRUCT_AMOUNT
            }
            break;
        // Ulduar
        case 4273:
            if (instance && mapid == 603)
                instance->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(4132) << uint32(0);              // 9  WORLDSTATE_SHOW_CRATES
                l_Buffer << uint32(4131) << uint32(0);              // 10 WORLDSTATE_CRATES_REVEALED
            }
            break;
        // Twin Peaks
        case 5031:
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_TP)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0x62d) << uint32(0x0);       //  7 1581 alliance flag captures
                l_Buffer << uint32(0x62e) << uint32(0x0);       //  8 1582 horde flag captures
                l_Buffer << uint32(0x609) << uint32(0x0);       //  9 1545 unk
                l_Buffer << uint32(0x60a) << uint32(0x0);       // 10 1546 unk
                l_Buffer << uint32(0x60b) << uint32(0x2);       // 11 1547 unk
                l_Buffer << uint32(0x641) << uint32(0x3);       // 12 1601 unk
                l_Buffer << uint32(0x922) << uint32(0x1);       // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
                l_Buffer << uint32(0x923) << uint32(0x1);       // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
            }
            break;
        // Battle for Gilneas
        case 5449:
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_BFG)
                bg->FillInitialWorldStates(l_Buffer);
            break;
        // Halls of Reflection
        case 4820:
            if (instance && mapid == 668)
                instance->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(4884) << uint32(0);              // 9 WORLD_STATE_HOR_WAVES_ENABLED
                l_Buffer << uint32(4882) << uint32(0);              // 10 WORLD_STATE_HOR_WAVE_COUNT
            }
            break;
        case 5833:
            l_Buffer << uint32(0x1958) << uint32(0x1);
            l_Buffer << uint32(0x1959) << uint32(0x4);
            break;
        // Silvershard Mines
        case 6126:
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_SM)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0x1924) << uint32(1);            // SM_MINE_CARTS_DISPLAY
                l_Buffer << uint32(0x1925) << uint32(0);            // SM_ALLIANCE_RESOURCES
                l_Buffer << uint32(0x1926) << uint32(0);            // SM_HORDE_RESOURCES
                l_Buffer << uint32(0x1927) << uint32(1);            // SM_MINE_CART_1
                l_Buffer << uint32(0x1928) << uint32(1);            // SM_MINE_CART_2
                l_Buffer << uint32(0x1929) << uint32(1);            // SM_DISPLAY_ALLIANCE_RESSOURCES
                l_Buffer << uint32(0x192a) << uint32(1);            // SM_MINE_CART_3
                l_Buffer << uint32(0x192b) << uint32(1);            // SM_DISPLAY_HORDE_RESSOURCES
                l_Buffer << uint32(0x1adb) << uint32(0);            // SM_DISPLAY_PROGRESS_BAR
                l_Buffer << uint32(0x1adc) << uint32(0);            // SM_PROGRESS_BAR_STATUS
                l_Buffer << uint32(0x1add) << uint32(0);            // SM_UNK
            }
            break;
        // Tol'Viron Arena
        case 6296:
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_TV)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0xE10) << uint32(0x0);           // 7 gold
                l_Buffer << uint32(0xE11) << uint32(0x0);           // 8 green
                l_Buffer << uint32(0xE1A) << uint32(0x0);           // 9 show
            }
            break;
        // The Tiger's Peak
        case 6732:
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_TTP)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(0xE10) << uint32(0x0);           // 7 gold
                l_Buffer << uint32(0xE11) << uint32(0x0);           // 8 green
                l_Buffer << uint32(0xE1A) << uint32(0x0);           // 9 show
            }
            break;
        // Deepwind Gorge
        case 6665:
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_DG)
                bg->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(7938) << uint32(1);          // WORLDSTATE_DG_GOLBIN_MINE
                l_Buffer << uint32(7939) << uint32(1);          // WORLDSTATE_DG_CENTER_MINE
                l_Buffer << uint32(7935) << uint32(1);          // WORLDSTATE_DG_PANDA_MINE
                l_Buffer << uint32(8230) << uint32(0);          // WORLDSTATE_DG_BASE_ALLIANCE
                l_Buffer << uint32(8231) << uint32(0);          // WORLDSTATE_DG_BASE_HORDE
                l_Buffer << uint32(7880) << uint32(0);          // WORLDSTATE_DG_SCORE_ALLIANCE
                l_Buffer << uint32(7881) << uint32(0);          // WORLDSTATE_DG_SCORE_HORDE
                l_Buffer << uint32(7904) << uint32(1);          // WORLDSTATE_DG_CART_ALLIANCE
                l_Buffer << uint32(7887) << uint32(1);          // WORLDSTATE_DG_CART_HORDE
            }
            break;
        // Ashran
        case 6941:
            if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_ASHRAN)
                pvp->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(521) << uint32(0);
                l_Buffer << uint32(522) << uint32(0);
                l_Buffer << uint32(523) << uint32(0);
                l_Buffer << uint32(524) << uint32(0);
                l_Buffer << uint32(1581) << uint32(0);
                l_Buffer << uint32(1582) << uint32(0);
                l_Buffer << uint32(1723) << uint32(0);
                l_Buffer << uint32(1724) << uint32(0);
                l_Buffer << uint32(1941) << uint32(0);
                l_Buffer << uint32(1942) << uint32(0);
                l_Buffer << uint32(1943) << uint32(0);
                l_Buffer << uint32(2259) << uint32(0);
                l_Buffer << uint32(2260) << uint32(0);
                l_Buffer << uint32(2261) << uint32(0);
                l_Buffer << uint32(2262) << uint32(0);
                l_Buffer << uint32(2263) << uint32(0);
                l_Buffer << uint32(2264) << uint32(0);
                l_Buffer << uint32(2265) << uint32(142);
                l_Buffer << uint32(2851) << uint32(0);
                l_Buffer << uint32(3085) << uint32(379);
                l_Buffer << uint32(3191) << uint32(16);
                l_Buffer << uint32(3327) << uint32(0);
                l_Buffer << uint32(3426) << uint32(3);
                l_Buffer << uint32(3600) << uint32(0);
                l_Buffer << uint32(3601) << uint32(0);
                l_Buffer << uint32(3610) << uint32(1);
                l_Buffer << uint32(3695) << uint32(0);
                l_Buffer << uint32(3710) << uint32(0);
                l_Buffer << uint32(3781) << uint32(0);
                l_Buffer << uint32(3801) << uint32(1);
                l_Buffer << uint32(3826) << uint32(4);
                l_Buffer << uint32(3901) << uint32(3);
                l_Buffer << uint32(4020) << uint32(1094);
                l_Buffer << uint32(4021) << uint32(7);
                l_Buffer << uint32(4022) << uint32(3);
                l_Buffer << uint32(4023) << uint32(4);
                l_Buffer << uint32(4024) << uint32(825);
                l_Buffer << uint32(4025) << uint32(269);
                l_Buffer << uint32(4062) << uint32(0);
                l_Buffer << uint32(4131) << uint32(60);
                l_Buffer << uint32(4273) << uint32(0);
                l_Buffer << uint32(4354) << uint32(time(NULL));
                l_Buffer << uint32(4375) << uint32(0);
                l_Buffer << uint32(4417) << uint32(1);
                l_Buffer << uint32(4418) << uint32(50);
                l_Buffer << uint32(4419) << uint32(0);
                l_Buffer << uint32(4485) << uint32(0);
                l_Buffer << uint32(4486) << uint32(0);
                l_Buffer << uint32(4862) << uint32(1000);
                l_Buffer << uint32(4863) << uint32(300);
                l_Buffer << uint32(4864) << uint32(100);
                l_Buffer << uint32(5037) << uint32(6);
                l_Buffer << uint32(5071) << uint32(6);
                l_Buffer << uint32(5115) << uint32(0);
                l_Buffer << uint32(5192) << uint32(0);
                l_Buffer << uint32(5193) << uint32(0);
                l_Buffer << uint32(5194) << uint32(0);
                l_Buffer << uint32(5195) << uint32(0);
                l_Buffer << uint32(5196) << uint32(0);
                l_Buffer << uint32(5332) << uint32(time(NULL));
                l_Buffer << uint32(5333) << uint32(0);
                l_Buffer << uint32(5334) << uint32(1);
                l_Buffer << uint32(5344) << uint32(0);
                l_Buffer << uint32(5360) << uint32(0);
                l_Buffer << uint32(5361) << uint32(0);
                l_Buffer << uint32(5508) << uint32(1);
                l_Buffer << uint32(5677) << uint32(0);
                l_Buffer << uint32(5678) << uint32(0);
                l_Buffer << uint32(5679) << uint32(0);
                l_Buffer << uint32(5684) << uint32(0);
                l_Buffer << uint32(6078) << uint32(0);
                l_Buffer << uint32(6095) << uint32(0);
                l_Buffer << uint32(6164) << uint32(35);
                l_Buffer << uint32(6174) << uint32(0);
                l_Buffer << uint32(6267) << uint32(25);
                l_Buffer << uint32(6306) << uint32(0);
                l_Buffer << uint32(6436) << uint32(0);
                l_Buffer << uint32(6895) << uint32(10);
                l_Buffer << uint32(6897) << uint32(10);
                l_Buffer << uint32(6898) << uint32(10);
                l_Buffer << uint32(7022) << uint32(0);
                l_Buffer << uint32(7242) << uint32(82);
                l_Buffer << uint32(7243) << uint32(1);
                l_Buffer << uint32(7244) << uint32(82);
                l_Buffer << uint32(7245) << uint32(1);
                l_Buffer << uint32(7511) << uint32(0);
                l_Buffer << uint32(7617) << uint32(5);
                l_Buffer << uint32(7618) << uint32(5);
                l_Buffer << uint32(7671) << uint32(0);
                l_Buffer << uint32(7738) << uint32(0);
                l_Buffer << uint32(7752) << uint32(0);
                l_Buffer << uint32(7774) << uint32(0);
                l_Buffer << uint32(7796) << uint32(0);
                l_Buffer << uint32(7797) << uint32(0);
                l_Buffer << uint32(7876) << uint32(0);
                l_Buffer << uint32(8012) << uint32(1);
                l_Buffer << uint32(8295) << uint32(15);
                l_Buffer << uint32(8306) << uint32(20);
                l_Buffer << uint32(8307) << uint32(20);
                l_Buffer << uint32(8391) << uint32(0);
                l_Buffer << uint32(8524) << uint32(0);
                l_Buffer << uint32(8525) << uint32(0);
                l_Buffer << uint32(8526) << uint32(0);
                l_Buffer << uint32(8527) << uint32(0);
                l_Buffer << uint32(8528) << uint32(0);
                l_Buffer << uint32(8529) << uint32(0);
                l_Buffer << uint32(8712) << uint32(0);
                l_Buffer << uint32(8722) << uint32(0);
                l_Buffer << uint32(8859) << uint32(0);
                l_Buffer << uint32(8860) << uint32(0);
                l_Buffer << uint32(8861) << uint32(0);
                l_Buffer << uint32(8862) << uint32(0);
                l_Buffer << uint32(8863) << uint32(1);
                l_Buffer << uint32(8890) << uint32(0);
                l_Buffer << uint32(8892) << uint32(0);
                l_Buffer << uint32(8911) << uint32(10);
                l_Buffer << uint32(8933) << uint32(65);
                l_Buffer << uint32(8934) << uint32(5);
                l_Buffer << uint32(8935) << uint32(1);
                l_Buffer << uint32(8938) << uint32(0);
                l_Buffer << uint32(8945) << uint32(time(NULL));
                l_Buffer << uint32(8946) << uint32(0);
                l_Buffer << uint32(8949) << uint32(1);
                l_Buffer << uint32(8950) << uint32(0);
                l_Buffer << uint32(8955) << uint32(0);
            }
            break;
        /// - Kotmogu Temple BG
        case 6051:
        {
            if (bg && bg->GetTypeID(true) == BATTLEGROUND_KT)
                bg->FillInitialWorldStates(l_Buffer);
            break;
        }
        ///< Upper Blackrock Spire
        case 7307:
        {
            if (instance && mapid == 1358)
                instance->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(9524) << uint32(0);              // WorldStateChickenTimer
                l_Buffer << uint32(9523) << uint32(0);              // WorldStateEnableChicken
            }

            break;
        }
        /// Highmaul
        case 6996:
        {
            if (instance && mapid == 1228)
                instance->FillInitialWorldStates(l_Buffer);
            else
            {
                l_Buffer << uint32(9722) << uint32(0); /// Iron Bombers - activation
                l_Buffer << uint32(9723) << uint32(0); /// Iron Bombers remaining
                l_Buffer << uint32(9724) << uint32(0); /// Drunken Bileslinger - activation
                l_Buffer << uint32(9725) << uint32(0); /// Drunken Bileslinger remaining
            }

            break;
        }
        default:
            l_Buffer << uint32(0x914) << uint32(0x0);           // 7
            l_Buffer << uint32(0x913) << uint32(0x0);           // 8
            l_Buffer << uint32(0x912) << uint32(0x0);           // 9
            l_Buffer << uint32(0x915) << uint32(0x0);           // 10
            break;
    }

    uint32 l_WorldStateCount = l_Buffer.size() / 8;
    l_Buffer.rpos(0);

    for (uint32 l_I = 0; l_I < l_WorldStateCount; ++l_I)
    {
        uint32 l_Field, l_Value;
        l_Buffer >> l_Field >> l_Value;

        SetWorldState(l_Field, l_Value);
    }

    WorldPacket data(SMSG_INIT_WORLD_STATES, 4 + 4 + 4 + 4 + l_Buffer.size());
    data << uint32(mapid);                                  // mapid
    data << uint32(zoneid);                                 // zone id
    data << uint32(areaid);                                 // area id, new 2.1.0
    data << uint32(l_WorldStateCount);
    data.append(l_Buffer);

    GetSession()->SendPacket(&data);

    SendBGWeekendWorldStates();
}

void Player::SendBGWeekendWorldStates()
{
    for (uint32 i = 1; i < sBattlemasterListStore.GetNumRows(); ++i)
    {
        BattlemasterListEntry const* bl = sBattlemasterListStore.LookupEntry(i);
        if (bl && bl->HolidayWorldState)
        {
            if (MS::Battlegrounds::BattlegroundMgr::IsBGWeekend((BattlegroundTypeId)bl->ID))
                SendUpdateWorldState(bl->HolidayWorldState, 1);
            else
                SendUpdateWorldState(bl->HolidayWorldState, 0);
        }
    }
}

uint32 Player::GetXPRestBonus(uint32 xp)
{
    uint32 rested_bonus = (uint32)GetRestBonus();           // xp for each rested bonus

    if (rested_bonus > xp)                                   // max rested_bonus == xp or (r+x) = 200% xp
        rested_bonus = xp;

    SetRestBonus(GetRestBonus() - rested_bonus);

    sLog->outInfo(LOG_FILTER_PLAYER, "Player gain %u xp (+ %u Rested Bonus). Rested points=%f", xp+rested_bonus, rested_bonus, GetRestBonus());
    return rested_bonus;
}

void Player::SetBindPoint(uint64 p_Guid)
{
    WorldPacket l_Data(SMSG_BINDER_CONFIRM, 2 + 16);
    l_Data.appendPackGUID(p_Guid);

    GetSession()->SendPacket(&l_Data);
}

void Player::SendTalentWipeConfirm(uint64 guid, bool specialization)
{
    uint32 cost = 0;

    if (!specialization)
        cost = sWorld->getBoolConfig(CONFIG_NO_RESET_TALENT_COST) ? 0 : GetNextResetTalentsCost();
    else
        cost = sWorld->getBoolConfig(CONFIG_NO_RESET_TALENT_COST) ? 0 : GetNextResetSpecializationCost();

    cost = cost > MAX_TALENT_WIPE_COST ? MAX_TALENT_WIPE_COST : cost;

    WorldPacket data(SMSG_RESPEC_WIPE_CONFIRM);

    data << uint8(specialization); // 0 : talent 1 : specialization
    data << uint32(cost);
    data.appendPackGUID(guid);

    GetSession()->SendPacket(&data);
}

/*********************************************************/
/***                    STORAGE SYSTEM                 ***/
/*********************************************************/
void Player::SetVirtualItemSlot(uint8 i, Item* item)
{
    ASSERT(i < 3);
    if (i < 2 && item)
    {
        if (!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
            return;
        uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
        if (charges == 0)
            return;
        if (charges > 1)
            item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT, charges-1);
        else if (charges <= 1)<--- Condition 'charges<=1' is always true
        {
            ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, false);
            item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
        }
    }
}

void Player::SetSheath(SheathState sheathed)
{
    switch (sheathed)
    {
        case SHEATH_STATE_UNARMED:                          // no prepared weapon
            SetVirtualItemSlot(0, NULL);
            SetVirtualItemSlot(1, NULL);
            SetVirtualItemSlot(2, NULL);
            break;
        case SHEATH_STATE_MELEE:                            // prepared melee weapon
            SetVirtualItemSlot(0, GetWeaponForAttack(WeaponAttackType::BaseAttack, true));
            SetVirtualItemSlot(1, GetWeaponForAttack(WeaponAttackType::OffAttack, true));
            SetVirtualItemSlot(2, NULL);
            break;
        case SHEATH_STATE_RANGED:                           // prepared ranged weapon
            SetVirtualItemSlot(0, NULL);
            SetVirtualItemSlot(1, NULL);
            SetVirtualItemSlot(2, GetWeaponForAttack(WeaponAttackType::RangedAttack, true));
            break;
        default:
            SetVirtualItemSlot(0, NULL);
            SetVirtualItemSlot(1, NULL);
            SetVirtualItemSlot(2, NULL);
            break;
    }

    Unit::SetSheath(sheathed);                              // this must visualize Sheath changing for other players...
}

uint8 Player::GetGuessedEquipSlot(ItemTemplate const* proto) const
{
    switch (proto->InventoryType)
    {
        case INVTYPE_HEAD:
            return EQUIPMENT_SLOT_HEAD;
        case INVTYPE_NECK:
            return EQUIPMENT_SLOT_NECK;
        case INVTYPE_SHOULDERS:
            return EQUIPMENT_SLOT_SHOULDERS;
        case INVTYPE_BODY:
            return EQUIPMENT_SLOT_BODY;
        case INVTYPE_CHEST:
            return EQUIPMENT_SLOT_CHEST;
        case INVTYPE_ROBE:
            return EQUIPMENT_SLOT_CHEST;
        case INVTYPE_WAIST:
            return EQUIPMENT_SLOT_WAIST;
        case INVTYPE_LEGS:
            return EQUIPMENT_SLOT_LEGS;
        case INVTYPE_FEET:
            return EQUIPMENT_SLOT_FEET;
        case INVTYPE_WRISTS:
            return EQUIPMENT_SLOT_WRISTS;
        case INVTYPE_HANDS:
            return EQUIPMENT_SLOT_HANDS;
        case INVTYPE_FINGER:
            return EQUIPMENT_SLOT_FINGER1;
        case INVTYPE_TRINKET:
            return EQUIPMENT_SLOT_TRINKET1;
        case INVTYPE_CLOAK:
            return EQUIPMENT_SLOT_BACK;
        case INVTYPE_WEAPON:
            return EQUIPMENT_SLOT_MAINHAND;
        case INVTYPE_SHIELD:
            return EQUIPMENT_SLOT_OFFHAND;
        case INVTYPE_RANGED:
            return EQUIPMENT_SLOT_MAINHAND;
        case INVTYPE_2HWEAPON:
            return EQUIPMENT_SLOT_MAINHAND;
        case INVTYPE_TABARD:
            return EQUIPMENT_SLOT_TABARD;
        case INVTYPE_WEAPONMAINHAND:
            return EQUIPMENT_SLOT_MAINHAND;
        case INVTYPE_WEAPONOFFHAND:
            return EQUIPMENT_SLOT_OFFHAND;
        case INVTYPE_HOLDABLE:
            return EQUIPMENT_SLOT_OFFHAND;
        case INVTYPE_THROWN:
            return EQUIPMENT_SLOT_MAINHAND;
        case INVTYPE_RANGEDRIGHT:
            return EQUIPMENT_SLOT_MAINHAND;
        case INVTYPE_BAG:
            return INVENTORY_SLOT_BAG_START;
        default:
            return NULL_SLOT;
    }
}

uint8 Player::FindEquipSlot(ItemTemplate const* proto, uint32 slot, bool swap) const
{
    uint8 playerClass = getClass();

    uint8 slots[4];
    slots[0] = NULL_SLOT;
    slots[1] = NULL_SLOT;
    slots[2] = NULL_SLOT;
    slots[3] = NULL_SLOT;
    switch (proto->InventoryType)
    {
        case INVTYPE_HEAD:
            slots[0] = EQUIPMENT_SLOT_HEAD;
            break;
        case INVTYPE_NECK:
            slots[0] = EQUIPMENT_SLOT_NECK;
            break;
        case INVTYPE_SHOULDERS:
            slots[0] = EQUIPMENT_SLOT_SHOULDERS;
            break;
        case INVTYPE_BODY:
            slots[0] = EQUIPMENT_SLOT_BODY;
            break;
        case INVTYPE_CHEST:
            slots[0] = EQUIPMENT_SLOT_CHEST;
            break;
        case INVTYPE_ROBE:
            slots[0] = EQUIPMENT_SLOT_CHEST;
            break;
        case INVTYPE_WAIST:
            slots[0] = EQUIPMENT_SLOT_WAIST;
            break;
        case INVTYPE_LEGS:
            slots[0] = EQUIPMENT_SLOT_LEGS;
            break;
        case INVTYPE_FEET:
            slots[0] = EQUIPMENT_SLOT_FEET;
            break;
        case INVTYPE_WRISTS:
            slots[0] = EQUIPMENT_SLOT_WRISTS;
            break;
        case INVTYPE_HANDS:
            slots[0] = EQUIPMENT_SLOT_HANDS;
            break;
        case INVTYPE_FINGER:
            slots[0] = EQUIPMENT_SLOT_FINGER1;
            slots[1] = EQUIPMENT_SLOT_FINGER2;
            break;
        case INVTYPE_TRINKET:
            slots[0] = EQUIPMENT_SLOT_TRINKET1;
            slots[1] = EQUIPMENT_SLOT_TRINKET2;
            break;
        case INVTYPE_CLOAK:
            slots[0] = EQUIPMENT_SLOT_BACK;
            break;
        case INVTYPE_WEAPON:
        {
            slots[0] = EQUIPMENT_SLOT_MAINHAND;

            // suggest offhand slot only if know dual wielding
            // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
            if (CanDualWield())
                slots[1] = EQUIPMENT_SLOT_OFFHAND;
            break;
        }
        case INVTYPE_SHIELD:
            slots[0] = EQUIPMENT_SLOT_OFFHAND;
            break;
        case INVTYPE_RANGED:
            slots[0] = EQUIPMENT_SLOT_MAINHAND;
            /*if (Item* mhWeapon = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND))
            {
                if (ItemTemplate const* mhWeaponProto = mhWeapon->GetTemplate())
                {
                    if (!CanTitanGrip() && mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                    {
                        const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                        break;
                    }
                }
            }

            if (GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
            {
                if (!CanTitanGrip() && proto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || proto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                {
                    const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                    break;
                }
            }*/
            break;
        case INVTYPE_2HWEAPON:
            slots[0] = EQUIPMENT_SLOT_MAINHAND;
           /* if (Item* mhWeapon = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND))
            {
                if (ItemTemplate const* mhWeaponProto = mhWeapon->GetTemplate())
                {
                    if (mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                    {
                        const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                        break;
                    }
                }
            }

            if (GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
            {
                if (proto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || proto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                {
                    const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                    break;
                }
            }*/
            if (CanDualWield() && CanTitanGrip() && proto->SubClass != ITEM_SUBCLASS_WEAPON_STAFF)
                slots[1] = EQUIPMENT_SLOT_OFFHAND;
            break;
        case INVTYPE_TABARD:
            slots[0] = EQUIPMENT_SLOT_TABARD;
            break;
        case INVTYPE_WEAPONMAINHAND:
            slots[0] = EQUIPMENT_SLOT_MAINHAND;
            break;
        case INVTYPE_WEAPONOFFHAND:
            slots[0] = EQUIPMENT_SLOT_OFFHAND;
            break;
        case INVTYPE_HOLDABLE:
            slots[0] = EQUIPMENT_SLOT_OFFHAND;
            break;
        case INVTYPE_THROWN:
            slots[0] = EQUIPMENT_SLOT_MAINHAND;
            slots[0] = EQUIPMENT_SLOT_MAINHAND;
            /*if (Item* mhWeapon = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND))
            {
                if (ItemTemplate const* mhWeaponProto = mhWeapon->GetTemplate())
                {
                    if (mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                    {
                        const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                        break;
                    }
                }
            }

            if (GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
            {
                if (proto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || proto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                {
                    const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                    break;
                }
            }*/
            break;
        case INVTYPE_RANGEDRIGHT:
            slots[0] = EQUIPMENT_SLOT_MAINHAND;
            /*if (Item* mhWeapon = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND))
            {
                if (ItemTemplate const* mhWeaponProto = mhWeapon->GetTemplate())
                {
                    if (mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                    {
                        const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                        break;
                    }
                }
            }

            if (GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
            {
                if (proto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || proto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                {
                    const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                    break;
                }
            }*/
            break;
        case INVTYPE_BAG:
            slots[0] = INVENTORY_SLOT_BAG_START + 0;
            slots[1] = INVENTORY_SLOT_BAG_START + 1;
            slots[2] = INVENTORY_SLOT_BAG_START + 2;
            slots[3] = INVENTORY_SLOT_BAG_START + 3;
            break;
        case INVTYPE_RELIC:
        {
           if (playerClass == CLASS_PALADIN || playerClass == CLASS_DRUID ||
               playerClass == CLASS_SHAMAN || playerClass == CLASS_DEATH_KNIGHT)
           {
               slots[0] = EQUIPMENT_SLOT_MAINHAND;
               /*if (Item* mhWeapon = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND))
               {
                   if (ItemTemplate const* mhWeaponProto = mhWeapon->GetTemplate())
                   {
                       if (mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || mhWeaponProto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                       {
                           const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                           break;
                       }
                   }
               }

               if (GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
               {
                   if (proto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM || proto->SubClass == ITEM_SUBCLASS_WEAPON_STAFF)
                   {
                       const_cast<Player*>(this)->AutoUnequipOffhandIfNeed(true);
                       break;
                   }
               }*/
           }
           break;
        }
        default:
            return NULL_SLOT;
    }

    if (slot != NULL_SLOT)
    {
        if (swap || !GetItemByPos(INVENTORY_SLOT_BAG_0, slot))
            for (uint8 i = 0; i < 4; ++i)
                if (slots[i] == slot)
                    return slot;
    }
    else
    {
        // search free slot at first
        for (uint8 i = 0; i < 4; ++i)
            if (slots[i] != NULL_SLOT && !GetItemByPos(INVENTORY_SLOT_BAG_0, slots[i]))
                // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
                if (slots[i] != EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
                    return slots[i];

        // if not found free and can swap return first appropriate from used
        for (uint8 i = 0; i < 4; ++i)
            if (slots[i] != NULL_SLOT && swap)
                return slots[i];
    }

    // no free position
    return NULL_SLOT;
}

InventoryResult Player::CanUnequipItems(uint32 item, uint32 count) const
{
    uint32 tempcount = 0;

    InventoryResult res = EQUIP_ERR_OK;

    for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->GetEntry() == item)
            {
                InventoryResult ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
                if (ires == EQUIP_ERR_OK)
                {
                    tempcount += pItem->GetCount();
                    if (tempcount >= count)
                        return EQUIP_ERR_OK;
                }
                else
                    res = ires;
            }

    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->GetEntry() == item)
            {
                tempcount += pItem->GetCount();
                if (tempcount >= count)
                    return EQUIP_ERR_OK;
            }


    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
        if (Bag* pBag = GetBagByPos(i))
            for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
                if (Item* pItem = GetItemByPos(i, j))
                    if (pItem->GetEntry() == item)
                    {
                        tempcount += pItem->GetCount();
                        if (tempcount >= count)
                            return EQUIP_ERR_OK;
                    }

    // not found req. item count and have unequippable items
    return res;
}

uint32 Player::GetItemCount(uint32 item, bool inBankAlso, Item* skipItem) const
{
    uint32 count = 0;
    for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem != skipItem &&  pItem->GetEntry() == item)
                count += pItem->GetCount();

    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
        if (Bag* pBag = GetBagByPos(i))
            count += pBag->GetItemCount(item, skipItem);

    if (skipItem && skipItem->GetTemplate()->GemProperties)
        for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
            if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                if (pItem != skipItem && pItem->GetTemplate()->Socket[0].Color)
                    count += pItem->GetGemCountWithID(item);

    if (inBankAlso)
    {
        // checking every item from 39 to 74 (including bank bags)
        for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_BAG_END; ++i)
            if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                if (pItem != skipItem && pItem->GetEntry() == item)
                    count += pItem->GetCount();

        for (uint8 i = REAGENT_BANK_SLOT_BAG_START; i < REAGENT_BANK_SLOT_BAG_END; ++i)
            if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                if (pItem != skipItem && pItem->GetEntry() == item)
                    count += pItem->GetCount();

        for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
            if (Bag* pBag = GetBagByPos(i))
                count += pBag->GetItemCount(item, skipItem);

        if (skipItem && skipItem->GetTemplate()->GemProperties)
            for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
                if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                    if (pItem != skipItem && pItem->GetTemplate()->Socket[0].Color)
                        count += pItem->GetGemCountWithID(item);
    }

    return count;
}

uint32 Player::GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem) const
{
    uint32 count = 0;
    for (int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem != skipItem)
                if (ItemTemplate const* pProto = pItem->GetTemplate())
                    if (pProto->ItemLimitCategory == limitCategory)
                        count += pItem->GetCount();

    for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
        if (Bag* pBag = GetBagByPos(i))
            count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem);

    for (int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_BAG_END; ++i)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem != skipItem)
                if (ItemTemplate const* pProto = pItem->GetTemplate())
                    if (pProto->ItemLimitCategory == limitCategory)
                        count += pItem->GetCount();

    for (int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
        if (Bag* pBag = GetBagByPos(i))
            count += pBag->GetItemCountWithLimitCategory(limitCategory, skipItem);

    return count;
}

Item* Player::GetItemByGuid(uint64 guid) const
{
    for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))		
            if (pItem->GetGUID() == guid)		
                return pItem;		
		
    for (int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_BAG_END; ++i)		
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))		
            if (pItem->GetGUID() == guid)		
                return pItem;		
		
    for (uint8 i = REAGENT_BANK_SLOT_BAG_START; i < REAGENT_BANK_SLOT_BAG_END; ++i)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->GetGUID() == guid)
                return pItem;

    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
        if (Bag* pBag = GetBagByPos(i))
            for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
                if (Item* pItem = pBag->GetItemByPos(j))
                    if (pItem->GetGUID() == guid)
                        return pItem;

    for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
        if (Bag* pBag = GetBagByPos(i))
            for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
                if (Item* pItem = pBag->GetItemByPos(j))
                    if (pItem->GetGUID() == guid)
                        return pItem;

    return NULL;
}

Item* Player::GetItemByPos(uint16 pos) const
{
    uint8 bag = pos >> 8;
    uint8 slot = pos & 255;
    return GetItemByPos(bag, slot);
}

Item* Player::GetItemByPos(uint8 bag, uint8 slot) const
{
    if (bag == INVENTORY_SLOT_BAG_0 && (slot < REAGENT_BANK_SLOT_BAG_END))
        return m_items[slot];
    else if (Bag* pBag = GetBagByPos(bag))
        return pBag->GetItemByPos(slot);

    return NULL;
}

Bag* Player::GetBagByPos(uint8 bag) const
{
    if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
        || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END))
        if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, bag))
            return item->ToBag();
    return NULL;
}

Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable /*= false*/) const
{
    uint8 slot;
    switch (attackType)
    {
        case WeaponAttackType::BaseAttack:   slot = EQUIPMENT_SLOT_MAINHAND; break;
        case WeaponAttackType::OffAttack:    slot = EQUIPMENT_SLOT_OFFHAND;  break;
        case WeaponAttackType::RangedAttack: slot = EQUIPMENT_SLOT_MAINHAND;   break;
        default: return NULL;
    }

    Item* item = NULL;
    if (useable)
        item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, slot);
    else
        item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
    if (!item || item->GetTemplate()->Class != ITEM_CLASS_WEAPON)
        return NULL;

    if (!useable)
        return item;

    if (item->CantBeUse() || IsInFeralForm())
        return NULL;

    return item;
}

Item* Player::GetShield(bool useable) const
{
    Item* item = NULL;
    if (useable)
        item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
    else
        item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
    if (!item || item->GetTemplate()->Class != ITEM_CLASS_ARMOR)
        return NULL;

    if (!useable)
        return item;

    if (item->CantBeUse())
        return NULL;

    return item;
}

uint8 Player::GetAttackBySlot(uint8 slot)
{
    switch (slot)
    {
        case EQUIPMENT_SLOT_MAINHAND: return WeaponAttackType::BaseAttack;
        case EQUIPMENT_SLOT_OFFHAND:  return WeaponAttackType::OffAttack;
        default:                      return WeaponAttackType::MaxAttack;
    }
}

bool Player::IsInventoryPos(uint8 bag, uint8 slot)
{
    if (bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT)
        return true;
    if (bag == INVENTORY_SLOT_BAG_0 && (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END))
        return true;
    if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
        return true;
    return false;
}

bool Player::IsEquipmentPos(uint8 bag, uint8 slot)
{
    if (bag == INVENTORY_SLOT_BAG_0 && (slot < EQUIPMENT_SLOT_END))
        return true;
    if (bag == INVENTORY_SLOT_BAG_0 && (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END))
        return true;
    return false;
}

bool Player::IsBankPos(uint8 bag, uint8 slot)
{
    if (bag == INVENTORY_SLOT_BAG_0 && (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END))
        return true;
    if (bag == INVENTORY_SLOT_BAG_0 && (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END))
        return true;
    if (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END)
        return true;
    return false;
}

bool Player::IsReagentBankPos(uint8 bag, uint8 slot)
{
    if (bag == INVENTORY_SLOT_BAG_0 && (slot >= REAGENT_BANK_SLOT_BAG_START && slot < REAGENT_BANK_SLOT_BAG_END))
        return true;
    if (bag >= REAGENT_BANK_SLOT_BAG_START && bag < REAGENT_BANK_SLOT_BAG_END)
        return true;

    return false;
}

bool Player::IsBagPos(uint16 pos)
{
    uint8 bag = pos >> 8;
    uint8 slot = pos & 255;
    if (bag == INVENTORY_SLOT_BAG_0 && (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END))
        return true;
    if (bag == INVENTORY_SLOT_BAG_0 && (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END))
        return true;
    return false;
}

bool Player::IsValidPos(uint8 bag, uint8 slot, bool explicit_pos)
{
    // post selected
    if (bag == NULL_BAG && !explicit_pos)
        return true;

    if (bag == INVENTORY_SLOT_BAG_0)
    {
        // any post selected
        if (slot == NULL_SLOT && !explicit_pos)
            return true;

        // equipment
        if (slot < EQUIPMENT_SLOT_END)
            return true;

        // bag equip slots
        if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
            return true;

        // backpack slots
        if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
            return true;

        // bank main slots
        if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
            return true;

        // bank bag slots
        if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
            return true;

        // reagent bank bag slots
        if (slot >= REAGENT_BANK_SLOT_BAG_START && slot < REAGENT_BANK_SLOT_BAG_END)
            return true;

        return false;
    }

    // bag content slots
    // bank bag content slots
    if (Bag* pBag = GetBagByPos(bag))
    {
        // any post selected
        if (slot == NULL_SLOT && !explicit_pos)
            return true;

        return slot < pBag->GetBagSize();
    }

    // where this?
    return false;
}

bool Player::HasItemCount(uint32 item, uint32 count, bool inBankAlso) const
{
    uint32 tempcount = 0;
    for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
        if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
        {
            tempcount += pItem->GetCount();
            if (tempcount >= count)
                return true;
        }
    }

    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        if (Bag* pBag = GetBagByPos(i))
        {
            for (uint32 j = 0; j < pBag->GetBagSize(); j++)
            {
                Item* pItem = GetItemByPos(i, j);
                if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
                {
                    tempcount += pItem->GetCount();
                    if (tempcount >= count)
                        return true;
                }
            }
        }
    }

    if (inBankAlso)
    {
        for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
        {
            Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
            if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
            {
                tempcount += pItem->GetCount();
                if (tempcount >= count)
                    return true;
            }
        }
        for (uint8 i = REAGENT_BANK_SLOT_BAG_START; i < REAGENT_BANK_SLOT_BAG_END; i++)
        {
            Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
            if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
            {
                tempcount += pItem->GetCount();
                if (tempcount >= count)
                    return true;
            }
        }
        for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
        {
            if (Bag* pBag = GetBagByPos(i))
            {
                for (uint32 j = 0; j < pBag->GetBagSize(); j++)
                {
                    Item* pItem = GetItemByPos(i, j);
                    if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
                    {
                        tempcount += pItem->GetCount();
                        if (tempcount >= count)
                            return true;
                    }
                }
            }
        }
    }

    return false;
}

bool Player::HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_slot) const
{
    uint32 tempcount = 0;
    for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        if (i == except_slot)
            continue;

        Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
        if (pItem && pItem->GetEntry() == item)
        {
            tempcount += pItem->GetCount();
            if (tempcount >= count)
                return true;
        }
    }

    ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
    if (pProto && pProto->GemProperties)
    {
        for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
        {
            if (i == except_slot)
                continue;

            Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
            if (pItem && pItem->GetTemplate()->Socket[0].Color)
            {
                tempcount += pItem->GetGemCountWithID(item);
                if (tempcount >= count)
                    return true;
            }
        }
    }

    return false;
}

bool Player::HasItemOrGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot) const
{
    uint32 tempcount = 0;
    for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        if (i == except_slot)
            continue;

        Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
        if (!pItem)
            continue;

        ItemTemplate const* pProto = pItem->GetTemplate();
        if (!pProto)
            continue;

        if (pProto->ItemLimitCategory == limitCategory)
        {
            tempcount += pItem->GetCount();
            if (tempcount >= count)
                return true;
        }

        if (pProto->Socket[0].Color || pItem->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT))
        {
            tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
            if (tempcount >= count)
                return true;
        }
    }

    return false;
}

InventoryResult Player::CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count) const
{
    ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(entry);
    if (!pProto)
    {
        if (no_space_count)
            *no_space_count = count;
        return EQUIP_ERR_ITEM_MAX_COUNT;
    }

    if (pItem && pItem->m_lootGenerated)
        return EQUIP_ERR_LOOT_GONE;

    // no maximum
    if ((pProto->MaxCount <= 0 && pProto->ItemLimitCategory == 0) || pProto->MaxCount == 2147483647)
        return EQUIP_ERR_OK;

    if (pProto->MaxCount > 0)
    {
        uint32 curcount = GetItemCount(pProto->ItemId, true, pItem);
        if (curcount + count > uint32(pProto->MaxCount))
        {
            if (no_space_count)
                *no_space_count = count + curcount - pProto->MaxCount;
            return EQUIP_ERR_ITEM_MAX_COUNT;
        }
    }

    // check unique-equipped limit
    if (pProto->ItemLimitCategory)
    {
        ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(pProto->ItemLimitCategory);
        if (!limitEntry)
        {
            if (no_space_count)
                *no_space_count = count;
            return EQUIP_ERR_NOT_EQUIPPABLE;
        }

        if (limitEntry->mode == ITEM_LIMIT_CATEGORY_MODE_HAVE)
        {
            uint32 curcount = GetItemCountWithLimitCategory(pProto->ItemLimitCategory, pItem);
            if (curcount + count > uint32(limitEntry->maxCount))
            {
                if (no_space_count)
                    *no_space_count = count + curcount - limitEntry->maxCount;
                return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS;
            }
        }
    }

    return EQUIP_ERR_OK;
}

InventoryResult Player::CanStoreItem_InSpecificSlot(uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemTemplate const* pProto, uint32& count, bool swap, Item* pSrcItem) const
{
    Item* pItem2 = GetItemByPos(bag, slot);

    // ignore move item (this slot will be empty at move)
    if (pItem2 == pSrcItem)
        pItem2 = NULL;

    uint32 need_space;

    if (pSrcItem && pSrcItem->IsNotEmptyBag() && !IsBagPos(uint16(bag) << 8 | slot))
        return EQUIP_ERR_DESTROY_NONEMPTY_BAG;

    // empty specific slot - check item fit to slot
    if (!pItem2 || swap)
    {
        if (bag == INVENTORY_SLOT_BAG_0)
        {
            // prevent cheating
            if ((slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END) || slot >= PLAYER_SLOT_END)
                return EQUIP_ERR_WRONG_BAG_TYPE;
        }
        else
        {
            Bag* pBag = GetBagByPos(bag);
            if (!pBag)
                return EQUIP_ERR_WRONG_BAG_TYPE;

            ItemTemplate const* pBagProto = pBag->GetTemplate();
            if (!pBagProto)
                return EQUIP_ERR_WRONG_BAG_TYPE;

            if (slot >= pBagProto->ContainerSlots)
                return EQUIP_ERR_WRONG_BAG_TYPE;

            if (!ItemCanGoIntoBag(pProto, pBagProto))
                return EQUIP_ERR_WRONG_BAG_TYPE;
        }

        // non empty stack with space
        need_space = pProto->GetMaxStackSize();
    }
    // non empty slot, check item type
    else
    {
        // can be merged at least partly
        InventoryResult res  = pItem2->CanBeMergedPartlyWith(pProto);
        if (res != EQUIP_ERR_OK)
            return res;

        // free stack space or infinity
        need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
    }

    if (need_space > count)
        need_space = count;

    ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
    if (!newPosition.isContainedIn(dest))
    {
        dest.push_back(newPosition);
        count -= need_space;
    }
    return EQUIP_ERR_OK;
}

InventoryResult Player::CanStoreItem_InBag(uint8 bag, ItemPosCountVec &dest, ItemTemplate const* pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const
{
    // skip specific bag already processed in first called CanStoreItem_InBag
    if (bag == skip_bag)
        return EQUIP_ERR_WRONG_BAG_TYPE;

    // skip not existed bag or self targeted bag
    Bag* pBag = GetBagByPos(bag);
    if (!pBag || pBag == pSrcItem)
        return EQUIP_ERR_WRONG_BAG_TYPE;

    if (pSrcItem && pSrcItem->IsNotEmptyBag())
        return EQUIP_ERR_DESTROY_NONEMPTY_BAG;

    ItemTemplate const* pBagProto = pBag->GetTemplate();
    if (!pBagProto)
        return EQUIP_ERR_WRONG_BAG_TYPE;

    // specialized bag mode or non-specilized
    if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
        return EQUIP_ERR_WRONG_BAG_TYPE;

    if (!ItemCanGoIntoBag(pProto, pBagProto))
        return EQUIP_ERR_WRONG_BAG_TYPE;

    for (uint32 j = 0; j < pBag->GetBagSize(); j++)
    {
        // skip specific slot already processed in first called CanStoreItem_InSpecificSlot
        if (j == skip_slot)
            continue;

        Item* pItem2 = GetItemByPos(bag, j);

        // ignore move item (this slot will be empty at move)
        if (pItem2 == pSrcItem)
            pItem2 = NULL;

        // if merge skip empty, if !merge skip non-empty
        if ((pItem2 != NULL) != merge)
            continue;

        uint32 need_space = pProto->GetMaxStackSize();

        if (pItem2)
        {
            // can be merged at least partly
            uint8 res  = pItem2->CanBeMergedPartlyWith(pProto);
            if (res != EQUIP_ERR_OK)
                continue;

            // descrease at current stacksize
            need_space -= pItem2->GetCount();
        }

        if (need_space > count)
            need_space = count;

        ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
        if (!newPosition.isContainedIn(dest))
        {
            dest.push_back(newPosition);
            count -= need_space;

            if (count==0)
                return EQUIP_ERR_OK;
        }
    }
    return EQUIP_ERR_OK;
}

InventoryResult Player::CanStoreItem_InInventorySlots(uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemTemplate const* pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot) const
{
    //this is never called for non-bag slots so we can do this
    if (pSrcItem && pSrcItem->IsNotEmptyBag())
        return EQUIP_ERR_DESTROY_NONEMPTY_BAG;

    for (uint32 j = slot_begin; j < slot_end; j++)
    {
        // skip specific slot already processed in first called CanStoreItem_InSpecificSlot
        if (INVENTORY_SLOT_BAG_0 == skip_bag && j == skip_slot)
            continue;

        Item* pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, j);

        // ignore move item (this slot will be empty at move)
        if (pItem2 == pSrcItem)
            pItem2 = NULL;

        // if merge skip empty, if !merge skip non-empty
        if ((pItem2 != NULL) != merge)
            continue;

        uint32 need_space = pProto->GetMaxStackSize();

        if (pItem2)
        {
            // can be merged at least partly
            uint8 res  = pItem2->CanBeMergedPartlyWith(pProto);
            if (res != EQUIP_ERR_OK)
                continue;

            // descrease at current stacksize
            need_space -= pItem2->GetCount();
        }

        if (need_space > count)
            need_space = count;

        ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
        if (!newPosition.isContainedIn(dest))
        {
            dest.push_back(newPosition);
            count -= need_space;

            if (count==0)
                return EQUIP_ERR_OK;
        }
    }
    return EQUIP_ERR_OK;
}

InventoryResult Player::CanStoreItem(uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item* pItem, bool swap, uint32* no_space_count) const
{
    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);

    ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(entry);
    if (!pProto)
    {
        if (no_space_count)
            *no_space_count = count;
        return swap ? EQUIP_ERR_CANT_SWAP :EQUIP_ERR_ITEM_NOT_FOUND;
    }

    if (pItem)
    {
        // item used
        if (pItem->m_lootGenerated)
        {
            if (no_space_count)
                *no_space_count = count;
            return EQUIP_ERR_LOOT_GONE;
        }

        if (pItem->IsBindedNotWith(this))
        {
            if (no_space_count)
                *no_space_count = count;
            return EQUIP_ERR_NOT_OWNER;
        }
    }

    // check count of items (skip for auto move for same player from bank)
    uint32 no_similar_count = 0;                            // can't store this amount similar items
    InventoryResult res = CanTakeMoreSimilarItems(entry, count, pItem, &no_similar_count);
    if (res != EQUIP_ERR_OK)
    {
        if (count == no_similar_count)
        {
            if (no_space_count)
                *no_space_count = no_similar_count;
            return res;
        }
        count -= no_similar_count;
    }

    // in specific slot
    if (bag != NULL_BAG && slot != NULL_SLOT)
    {
        res = CanStoreItem_InSpecificSlot(bag, slot, dest, pProto, count, swap, pItem);
        if (res != EQUIP_ERR_OK)
        {
            if (no_space_count)
                *no_space_count = count + no_similar_count;
            return res;
        }

        if (count == 0)
        {
            if (no_similar_count == 0)
                return EQUIP_ERR_OK;

            if (no_space_count)
                *no_space_count = count + no_similar_count;
            return EQUIP_ERR_ITEM_MAX_COUNT;
        }
    }

    // not specific slot or have space for partly store only in specific slot

    // in specific bag
    if (bag != NULL_BAG)
    {
        // search stack in bag for merge to
        if (pProto->Stackable != 1)
        {
            if (bag == INVENTORY_SLOT_BAG_0)               // inventory
            {
                res = CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START, INVENTORY_SLOT_ITEM_END, dest, pProto, count, true, pItem, bag, slot);
                if (res != EQUIP_ERR_OK)
                {
                    if (no_space_count)
                        *no_space_count = count + no_similar_count;
                    return res;
                }

                if (count == 0)
                {
                    if (no_similar_count == 0)
                        return EQUIP_ERR_OK;

                    if (no_space_count)
                        *no_space_count = count + no_similar_count;
                    return EQUIP_ERR_ITEM_MAX_COUNT;
                }
            }
            else                                            // equipped bag
            {
                // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
                res = CanStoreItem_InBag(bag, dest, pProto, count, true, false, pItem, NULL_BAG, slot);
                if (res != EQUIP_ERR_OK)
                    res = CanStoreItem_InBag(bag, dest, pProto, count, true, true, pItem, NULL_BAG, slot);

                if (res != EQUIP_ERR_OK)
                {
                    if (no_space_count)
                        *no_space_count = count + no_similar_count;
                    return res;
                }

                if (count == 0)
                {
                    if (no_similar_count == 0)
                        return EQUIP_ERR_OK;

                    if (no_space_count)
                        *no_space_count = count + no_similar_count;
                    return EQUIP_ERR_ITEM_MAX_COUNT;
                }
            }
        }

        // search free slot in bag for place to
        if (bag == INVENTORY_SLOT_BAG_0)                     // inventory
        {
            res = CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START, INVENTORY_SLOT_ITEM_END, dest, pProto, count, false, pItem, bag, slot);
            if (res != EQUIP_ERR_OK)
            {
                if (no_space_count)
                    *no_space_count = count + no_similar_count;
                return res;
            }

            if (count == 0)
            {
                if (no_similar_count == 0)
                    return EQUIP_ERR_OK;

                if (no_space_count)
                    *no_space_count = count + no_similar_count;
                return EQUIP_ERR_ITEM_MAX_COUNT;
            }
        }
        else                                                // equipped bag
        {
            res = CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
            if (res != EQUIP_ERR_OK)
                res = CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);

            if (res != EQUIP_ERR_OK)
            {
                if (no_space_count)
                    *no_space_count = count + no_similar_count;
                return res;
            }

            if (count == 0)
            {
                if (no_similar_count == 0)
                    return EQUIP_ERR_OK;

                if (no_space_count)
                    *no_space_count = count + no_similar_count;
                return EQUIP_ERR_ITEM_MAX_COUNT;
            }
        }
    }

    // not specific bag or have space for partly store only in specific bag

    // search stack for merge to
    if (pProto->Stackable != 1)
    {
        res = CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START, INVENTORY_SLOT_ITEM_END, dest, pProto, count, true, pItem, bag, slot);
        if (res != EQUIP_ERR_OK)
        {
            if (no_space_count)
                *no_space_count = count + no_similar_count;
            return res;
        }

        if (count == 0)
        {
            if (no_similar_count == 0)
                return EQUIP_ERR_OK;

            if (no_space_count)
                *no_space_count = count + no_similar_count;
            return EQUIP_ERR_ITEM_MAX_COUNT;
        }

        if (pProto->BagFamily)
        {
            for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
            {
                res = CanStoreItem_InBag(i, dest, pProto, count, true, false, pItem, bag, slot);
                if (res != EQUIP_ERR_OK)
                    continue;

                if (count == 0)
                {
                    if (no_similar_count == 0)
                        return EQUIP_ERR_OK;

                    if (no_space_count)
                        *no_space_count = count + no_similar_count;
                    return EQUIP_ERR_ITEM_MAX_COUNT;
                }
            }
        }

        for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
        {
            res = CanStoreItem_InBag(i, dest, pProto, count, true, true, pItem, bag, slot);
            if (res != EQUIP_ERR_OK)
                continue;

            if (count == 0)
            {
                if (no_similar_count == 0)
                    return EQUIP_ERR_OK;

                if (no_space_count)
                    *no_space_count = count + no_similar_count;
                return EQUIP_ERR_ITEM_MAX_COUNT;
            }
        }
    }

    // search free slot - special bag case
    if (pProto->BagFamily)
    {
        for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
        {
            res = CanStoreItem_InBag(i, dest, pProto, count, false, false, pItem, bag, slot);
            if (res != EQUIP_ERR_OK)
                continue;

            if (count == 0)
            {
                if (no_similar_count == 0)
                    return EQUIP_ERR_OK;

                if (no_space_count)
                    *no_space_count = count + no_similar_count;
                return EQUIP_ERR_ITEM_MAX_COUNT;
            }
        }
    }

    if (pItem && pItem->IsNotEmptyBag())
        return EQUIP_ERR_BAG_IN_BAG;

    // search free slot
    res = CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START, INVENTORY_SLOT_ITEM_END, dest, pProto, count, false, pItem, bag, slot);
    if (res != EQUIP_ERR_OK)
    {
        if (no_space_count)
            *no_space_count = count + no_similar_count;
        return res;
    }

    if (count == 0)
    {
        if (no_similar_count == 0)
            return EQUIP_ERR_OK;

        if (no_space_count)
            *no_space_count = count + no_similar_count;
        return EQUIP_ERR_ITEM_MAX_COUNT;
    }

    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        res = CanStoreItem_InBag(i, dest, pProto, count, false, true, pItem, bag, slot);
        if (res != EQUIP_ERR_OK)
            continue;

        if (count == 0)
        {
            if (no_similar_count == 0)
                return EQUIP_ERR_OK;

            if (no_space_count)
                *no_space_count = count + no_similar_count;
            return EQUIP_ERR_ITEM_MAX_COUNT;
        }
    }

    if (no_space_count)
        *no_space_count = count + no_similar_count;

    return EQUIP_ERR_INV_FULL;
}

//////////////////////////////////////////////////////////////////////////
InventoryResult Player::CanStoreItems(Item** pItems, int count) const
{
    Item* pItem2;

    // fill space table
    int inv_slot_items[INVENTORY_SLOT_ITEM_END - INVENTORY_SLOT_ITEM_START];
    int inv_bags[INVENTORY_SLOT_BAG_END - INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];

    memset(inv_slot_items, 0, sizeof(int) * (INVENTORY_SLOT_ITEM_END - INVENTORY_SLOT_ITEM_START));
    memset(inv_bags, 0, sizeof(int) * (INVENTORY_SLOT_BAG_END - INVENTORY_SLOT_BAG_START) * MAX_BAG_SIZE);

    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
        if (pItem2 && !pItem2->IsInTrade())
            inv_slot_items[i - INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
    }

    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
        if (Bag* pBag = GetBagByPos(i))
            for (uint32 j = 0; j < pBag->GetBagSize(); j++)
            {
                pItem2 = GetItemByPos(i, j);
                if (pItem2 && !pItem2->IsInTrade())
                    inv_bags[i - INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
            }

    // check free space for all items
    for (int k = 0; k < count; ++k)
    {
        Item* pItem = pItems[k];

        // no item
        if (!pItem)
            continue;

        sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanStoreItems %i. item = %u, count = %u", k + 1, pItem->GetEntry(), pItem->GetCount());
        ItemTemplate const* pProto = pItem->GetTemplate();

        // strange item
        if (!pProto)
            return EQUIP_ERR_ITEM_NOT_FOUND;

        // item used
        if (pItem->m_lootGenerated)
            return EQUIP_ERR_LOOT_GONE;

        // item it 'bind'
        if (pItem->IsBindedNotWith(this))
            return EQUIP_ERR_NOT_OWNER;

        ItemTemplate const* pBagProto;

        // item is 'one item only'
        InventoryResult res = CanTakeMoreSimilarItems(pItem);
        if (res != EQUIP_ERR_OK)
            return res;

        // search stack for merge to
        if (pProto->Stackable != 1)
        {
            bool b_found = false;

            for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
            {
                pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, t);
                if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
                {
                    inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
                    b_found = true;
                    break;
                }
            }
            if (b_found)
                continue;

            for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
            {
                if (Bag* bag = GetBagByPos(t))
                {
                    if (ItemCanGoIntoBag(pItem->GetTemplate(), bag->GetTemplate()))
                    {
                        for (uint32 j = 0; j < bag->GetBagSize(); j++)
                        {
                            pItem2 = GetItemByPos(t, j);
                            if (pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
                            {
                                inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
                                b_found = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (b_found)
                continue;
        }

        // special bag case
        if (pProto->BagFamily)
        {
            bool b_found = false;

            for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
            {
                if (Bag* bag = GetBagByPos(t))
                {
                    pBagProto = bag->GetTemplate();

                    // not plain container check
                    if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
                        ItemCanGoIntoBag(pProto, pBagProto))
                    {
                        for (uint32 j = 0; j < bag->GetBagSize(); j++)
                        {
                            if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0)
                            {
                                inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
                                b_found = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (b_found)
                continue;
        }

        // search free slot
        bool b_found = false;
        for (int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
        {
            if (inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0)
            {
                inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
                b_found = true;
                break;
            }
        }
        if (b_found)
            continue;

        // search free slot in bags
        for (int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
        {
            if (Bag* bag = GetBagByPos(t))
            {
                pBagProto = bag->GetTemplate();

                // special bag already checked
                if (pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
                    continue;

                for (uint32 j = 0; j < bag->GetBagSize(); j++)
                {
                    if (inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0)
                    {
                        inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
                        b_found = true;
                        break;
                    }
                }
            }
        }

        // no free slot found?
        if (!b_found)
            return EQUIP_ERR_INV_FULL;
    }

    return EQUIP_ERR_OK;
}

//////////////////////////////////////////////////////////////////////////
InventoryResult Player::CanEquipNewItem(uint8 slot, uint16 &dest, uint32 item, bool swap) const
{
    dest = 0;
    Item* pItem = Item::CreateItem(item, 1, this);
    if (pItem)
    {
        InventoryResult result = CanEquipItem(slot, dest, pItem, swap);
        delete pItem;
        return result;
    }

    return EQUIP_ERR_ITEM_NOT_FOUND;
}

InventoryResult Player::CanEquipItem(uint8 slot, uint16 &dest, Item* pItem, bool swap, bool not_loading) const
{
    dest = 0;
    if (pItem)
    {
        sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
        ItemTemplate const* pProto = pItem->GetTemplate();
        if (pProto)
        {
            // item used
            if (pItem->m_lootGenerated)
                return EQUIP_ERR_LOOT_GONE;

            if (pItem->IsBindedNotWith(this))
                return EQUIP_ERR_NOT_OWNER;

            // check count of items (skip for auto move for same player from bank)
            InventoryResult res = CanTakeMoreSimilarItems(pItem);
            if (res != EQUIP_ERR_OK)
                return res;

            // check this only in game
            if (not_loading)
            {
                // May be here should be more stronger checks; STUNNED checked
                // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
                if (HasUnitState(UNIT_STATE_STUNNED))
                    return EQUIP_ERR_GENERIC_STUNNED;

                // do not allow equipping gear except weapons, offhands, projectiles, relics in
                // - combat
                // - in-progress arenas
                if (!pProto->CanChangeEquipStateInCombat())
                {
                    if (isInCombat())
                        return EQUIP_ERR_NOT_IN_COMBAT;

                    if (Battleground* bg = GetBattleground())
                        if (bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS)
                            return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
                }

                if (pProto->Class == ITEM_CLASS_WEAPON && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED))
                    return EQUIP_ERR_CLIENT_LOCKED_OUT;

                if (isInCombat()&& (pProto->Class == ITEM_CLASS_WEAPON || pProto->InventoryType == INVTYPE_RELIC) && m_weaponChangeTimer != 0)
                    return EQUIP_ERR_CLIENT_LOCKED_OUT;         // maybe exist better err

                if (IsNonMeleeSpellCasted(false))
                    return EQUIP_ERR_CLIENT_LOCKED_OUT;
            }

            uint8 eslot = FindEquipSlot(pProto, slot, swap);
            if (eslot == NULL_SLOT)
                return EQUIP_ERR_NOT_EQUIPPABLE;

            res = CanUseItem(pItem, not_loading);
            if (res != EQUIP_ERR_OK)
                return res;

            if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
                return EQUIP_ERR_NO_SLOT_AVAILABLE;

            // if swap ignore item (equipped also)
            InventoryResult res2 = CanEquipUniqueItem(pItem, swap ? eslot : uint8(NULL_SLOT));
            if (res2 != EQUIP_ERR_OK)
                return res2;

            // check unique-equipped special item classes
            if (pProto->Class == ITEM_CLASS_QUIVER)
                for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
                    if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                        if (pBag != pItem)
                            if (ItemTemplate const* pBagProto = pBag->GetTemplate())
                                if (pBagProto->Class == pProto->Class && (!swap || pBag->GetSlot() != eslot))
                                    return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
                                        ? EQUIP_ERR_ONLY_ONE_AMMO
                                        : EQUIP_ERR_ONLY_ONE_QUIVER;

            uint32 type = pProto->InventoryType;

            if (eslot == EQUIPMENT_SLOT_OFFHAND)
            {
                // Do not allow polearm to be equipped in the offhand (rare case for the only 1h polearm 41750)
                if (type == INVTYPE_WEAPON && pProto->SubClass == ITEM_SUBCLASS_WEAPON_POLEARM)
                    return EQUIP_ERR_2HSKILLNOTFOUND;
                else if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
                {
                    if (!CanDualWield())
                        return EQUIP_ERR_2HSKILLNOTFOUND;
                }
                else if (type == INVTYPE_2HWEAPON)
                {
                    if (!CanDualWield() || !CanTitanGrip())
                        return EQUIP_ERR_2HSKILLNOTFOUND;
                }

                if (IsTwoHandUsed())
                    return EQUIP_ERR_2HANDED_EQUIPPED;
            }

            // equip two-hand weapon case (with possible unequip 2 items)
            /// Ranged weapons are two hands weapons since MoP
            if (type == INVTYPE_2HWEAPON || type == INVTYPE_RANGEDRIGHT)
            {
                if (eslot == EQUIPMENT_SLOT_OFFHAND)
                {
                    if (!CanTitanGrip())
                        return EQUIP_ERR_NOT_EQUIPPABLE;
                }
                else if (eslot != EQUIPMENT_SLOT_MAINHAND)
                    return EQUIP_ERR_NOT_EQUIPPABLE;

                if (!CanTitanGrip())
                {
                    // offhand item must can be stored in inventory for offhand item and it also must be unequipped
                    Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
                    ItemPosCountVec off_dest;
                    if (offItem && (!not_loading ||
                        CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND, false) != EQUIP_ERR_OK ||
                        CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false) != EQUIP_ERR_OK))
                        return swap ? EQUIP_ERR_CANT_SWAP : EQUIP_ERR_INV_FULL;
                }
            }
            dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
            return EQUIP_ERR_OK;
        }
    }

    return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_CANT_SWAP;
}

InventoryResult Player::CanUnequipItem(uint16 pos, bool swap) const
{
    // Applied only to equipped items and bank bags
    if (!IsEquipmentPos(pos) && !IsBagPos(pos))
        return EQUIP_ERR_OK;

    Item* pItem = GetItemByPos(pos);

    // Applied only to existed equipped item
    if (!pItem)
        return EQUIP_ERR_OK;

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());

    ItemTemplate const* pProto = pItem->GetTemplate();
    if (!pProto)
        return EQUIP_ERR_ITEM_NOT_FOUND;

    // item used
    if (pItem->m_lootGenerated)
        return EQUIP_ERR_LOOT_GONE;

    // do not allow unequipping gear except weapons, offhands, projectiles, relics in
    // - combat
    // - in-progress arenas
    if (!pProto->CanChangeEquipStateInCombat())
    {
        if (isInCombat())
            return EQUIP_ERR_NOT_IN_COMBAT;

        if (Battleground* bg = GetBattleground())
            if (bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS)
                return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
    }

    if ((pProto->Class & ITEM_CLASS_WEAPON) && HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISARMED))
        return EQUIP_ERR_CLIENT_LOCKED_OUT;

    if (!swap && pItem->IsNotEmptyBag())
        return EQUIP_ERR_DESTROY_NONEMPTY_BAG;

    return EQUIP_ERR_OK;
}

InventoryResult Player::CanBankItem(uint8 bag, uint8 slot, ItemPosCountVec &dest, Item* pItem, bool swap, bool not_loading) const
{
    if (!pItem)
        return swap ? EQUIP_ERR_CANT_SWAP : EQUIP_ERR_ITEM_NOT_FOUND;

    uint32 count = pItem->GetCount();

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
    ItemTemplate const* pProto = pItem->GetTemplate();
    if (!pProto)
        return swap ? EQUIP_ERR_CANT_SWAP : EQUIP_ERR_ITEM_NOT_FOUND;

    // item used
    if (pItem->m_lootGenerated)
        return EQUIP_ERR_LOOT_GONE;

    if (pItem->IsBindedNotWith(this))
        return EQUIP_ERR_NOT_OWNER;

    // Currency tokens are not supposed to be swapped out of their hidden bag
    if (pItem->IsCurrencyToken())
    {
        sLog->outError(LOG_FILTER_PLAYER, "Possible hacking attempt: Player %s [guid: %u] tried to move token [guid: %u, entry: %u] out of the currency bag!",
                GetName(), GetGUIDLow(), pItem->GetGUIDLow(), pProto->ItemId);
        return EQUIP_ERR_CANT_SWAP;
    }

    // check count of items (skip for auto move for same player from bank)
    InventoryResult res = CanTakeMoreSimilarItems(pItem);
    if (res != EQUIP_ERR_OK)
        return res;

    // in specific slot
    if (bag != NULL_BAG && slot != NULL_SLOT)
    {
        if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
        {
            if (!pItem->IsBag())
                return EQUIP_ERR_WRONG_SLOT;

            if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
                return EQUIP_ERR_NO_BANK_SLOT;

            res = CanUseItem(pItem, not_loading);
            if (res != EQUIP_ERR_OK)
                return res;
        }

        res = CanStoreItem_InSpecificSlot(bag, slot, dest, pProto, count, swap, pItem);
        if (res != EQUIP_ERR_OK)
            return res;

        if (count == 0)
            return EQUIP_ERR_OK;
    }

    // not specific slot or have space for partly store only in specific slot

    // in specific bag
    if (bag != NULL_BAG)
    {
        if (pItem->IsNotEmptyBag())
            return EQUIP_ERR_BAG_IN_BAG;

        // search stack in bag for merge to
        if (pProto->Stackable != 1)
        {
            if (bag == INVENTORY_SLOT_BAG_0)
            {
                res = CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START, BANK_SLOT_ITEM_END, dest, pProto, count, true, pItem, bag, slot);
                if (res != EQUIP_ERR_OK)
                    return res;

                if (count == 0)
                    return EQUIP_ERR_OK;
            }
            else
            {
                res = CanStoreItem_InBag(bag, dest, pProto, count, true, false, pItem, NULL_BAG, slot);
                if (res != EQUIP_ERR_OK)
                    res = CanStoreItem_InBag(bag, dest, pProto, count, true, true, pItem, NULL_BAG, slot);

                if (res != EQUIP_ERR_OK)
                    return res;

                if (count == 0)
                    return EQUIP_ERR_OK;
            }
        }

        // search free slot in bag
        if (bag == INVENTORY_SLOT_BAG_0)
        {
            res = CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START, BANK_SLOT_ITEM_END, dest, pProto, count, false, pItem, bag, slot);
            if (res != EQUIP_ERR_OK)
                return res;

            if (count == 0)
                return EQUIP_ERR_OK;
        }
        else
        {
            res = CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
            if (res != EQUIP_ERR_OK)
                res = CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);

            if (res != EQUIP_ERR_OK)
                return res;

            if (count == 0)
                return EQUIP_ERR_OK;
        }
    }

    // not specific bag or have space for partly store only in specific bag

    // search stack for merge to
    if (pProto->Stackable != 1)
    {
        // in slots
        res = CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START, BANK_SLOT_ITEM_END, dest, pProto, count, true, pItem, bag, slot);
        if (res != EQUIP_ERR_OK)
            return res;

        if (count == 0)
            return EQUIP_ERR_OK;

        // in special bags
        if (pProto->BagFamily)
        {
            for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
            {
                res = CanStoreItem_InBag(i, dest, pProto, count, true, false, pItem, bag, slot);
                if (res != EQUIP_ERR_OK)
                    continue;

                if (count == 0)
                    return EQUIP_ERR_OK;
            }
        }

        for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
        {
            res = CanStoreItem_InBag(i, dest, pProto, count, true, true, pItem, bag, slot);
            if (res != EQUIP_ERR_OK)
                continue;

            if (count == 0)
                return EQUIP_ERR_OK;
        }
    }

    // search free place in special bag
    if (pProto->BagFamily)
    {
        for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
        {
            res = CanStoreItem_InBag(i, dest, pProto, count, false, false, pItem, bag, slot);
            if (res != EQUIP_ERR_OK)
                continue;

            if (count == 0)
                return EQUIP_ERR_OK;
        }
    }

    // search free space
    res = CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START, BANK_SLOT_ITEM_END, dest, pProto, count, false, pItem, bag, slot);
    if (res != EQUIP_ERR_OK)
        return res;

    if (count == 0)
        return EQUIP_ERR_OK;

    for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
    {
        res = CanStoreItem_InBag(i, dest, pProto, count, false, true, pItem, bag, slot);
        if (res != EQUIP_ERR_OK)
            continue;

        if (count == 0)
            return EQUIP_ERR_OK;
    }
    return EQUIP_ERR_BANK_FULL;
}

bool Player::IsItemSupplies(ItemTemplate const *p_BagProto) const<--- The function 'IsItemSupplies' is never used.
{
    switch (p_BagProto->SubClass)
    {
        case ITEM_SUBCLASS_HERB_CONTAINER:
        case ITEM_SUBCLASS_ENGINEERING_CONTAINER:
        case ITEM_SUBCLASS_GEM_CONTAINER:
        case ITEM_SUBCLASS_ENCHANTING_CONTAINER:
        case ITEM_SUBCLASS_MINING_CONTAINER:
        case ITEM_SUBCLASS_LEATHERWORKING_CONTAINER:
        case ITEM_SUBCLASS_INSCRIPTION_CONTAINER:
        case ITEM_SUBCLASS_TACKLE_CONTAINER:
        case ITEM_SUBCLASS_COOKING_CONTAINER:
        case ITEM_SUBCLASS_ENCHANTING_CONTAINER_2:
        case ITEM_SUBCLASS_MATERIALS_CONTAINER:
        case ITEM_SUBCLASS_ITEM_ENCHANTMENT_CONTAINER:
        case ITEM_SUBCLASS_WEAPON_ENCHANTMENT_CONTAINER:
            return true;
    }
    return false;
}

InventoryResult Player::CanReagentBankItem(uint8 bag, uint8 slot, ItemPosCountVec &dest, Item* pItem, bool swap) const
{
    if (!pItem)
        return swap ? EQUIP_ERR_CANT_SWAP : EQUIP_ERR_ITEM_NOT_FOUND;

    uint32 count = pItem->GetCount();

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanReagentBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());

    ItemTemplate const* pProto = pItem->GetTemplate();
    if (!pProto)
        return swap ? EQUIP_ERR_CANT_SWAP : EQUIP_ERR_ITEM_NOT_FOUND;

    if ((pProto->Flags2 & ITEM_FLAG2_CRAFTING_MATERIAL) == 0)
        return EQUIP_ERR_WRONG_SLOT;

    if (pItem->IsBindedNotWith(this))
        return EQUIP_ERR_NOT_OWNER;

    // check count of items (skip for auto move for same player from bank)
    InventoryResult res = CanTakeMoreSimilarItems(pItem);

    if (res != EQUIP_ERR_OK)
        return res;

    // in specific slot
    if (bag != NULL_BAG && slot != NULL_SLOT)
    {
        res = CanStoreItem_InSpecificSlot(bag, slot, dest, pProto, count, swap, pItem);

        if (res != EQUIP_ERR_OK)
            return res;

        if (count == 0)
            return EQUIP_ERR_OK;
    }

    // search stack for merge to
    if (pProto->Stackable != 1)
    {
        // in slots
        res = CanStoreItem_InInventorySlots(REAGENT_BANK_SLOT_BAG_START, REAGENT_BANK_SLOT_BAG_END, dest, pProto, count, true, pItem, bag, slot);

        if (res != EQUIP_ERR_OK)
            return res;

        if (count == 0)
            return EQUIP_ERR_OK;
    }

    // search free space
    res = CanStoreItem_InInventorySlots(REAGENT_BANK_SLOT_BAG_START, REAGENT_BANK_SLOT_BAG_END, dest, pProto, count, false, pItem, bag, slot);

    if (res != EQUIP_ERR_OK)
        return res;

    if (count == 0)
        return EQUIP_ERR_OK;

    return EQUIP_ERR_BANK_FULL;
}

InventoryResult Player::CanUseItem(Item* pItem, bool not_loading) const
{
    if (pItem)
    {
        sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: CanUseItem item = %u", pItem->GetEntry());

        if (!isAlive() && not_loading)
            return EQUIP_ERR_PLAYER_DEAD;

        //if (isStunned())
        //    return EQUIP_ERR_GENERIC_STUNNED;

        ItemTemplate const* pProto = pItem->GetTemplate();
        if (pProto)
        {
            if (pItem->IsBindedNotWith(this))
                return EQUIP_ERR_NOT_OWNER;

            InventoryResult res = CanUseItem(pProto);
            if (res != EQUIP_ERR_OK)
                return res;

            if (pItem->GetSkill() != 0)
            {
                bool allowEquip = false;
                uint32 itemSkill = pItem->GetSkill();
                // Armor that is binded to account can "morph" from plate to mail, etc. if skill is not learned yet.
                if (pProto->Quality == ITEM_QUALITY_HEIRLOOM && pProto->Class == ITEM_CLASS_ARMOR && !HasSkill(itemSkill))
                {
                    // TODO: when you right-click already equipped item it throws EQUIP_ERR_PROFICIENCY_NEEDED.

                    // In fact it's a visual bug, everything works properly... I need sniffs of operations with
                    // binded to account items from off server.

                    switch (getClass())
                    {
                        case CLASS_HUNTER:
                        case CLASS_SHAMAN:
                            allowEquip = (itemSkill == SKILL_MAIL);
                            break;
                        case CLASS_PALADIN:
                        case CLASS_WARRIOR:
                            allowEquip = (itemSkill == SKILL_PLATE_MAIL);
                            break;
                    }
                }
                if (!allowEquip && GetSkillValue(itemSkill) == 0)
                    return EQUIP_ERR_PROFICIENCY_NEEDED;
            }

            if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
                return EQUIP_ERR_CANT_EQUIP_REPUTATION;

            return EQUIP_ERR_OK;
        }
    }
    return EQUIP_ERR_ITEM_NOT_FOUND;
}

InventoryResult Player::CanUseItem(ItemTemplate const* proto) const
{
    // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player

    if (proto)
    {
        if ((proto->Flags2 & ITEM_FLAG2_HORDE_ONLY) && GetTeam() != HORDE)
            return EQUIP_ERR_CANT_EQUIP_EVER;

        if ((proto->Flags2 & ITEM_FLAG2_ALLIANCE_ONLY) && GetTeam() != ALLIANCE)
            return EQUIP_ERR_CANT_EQUIP_EVER;

        if ((proto->AllowableClass & getClassMask()) == 0 || (proto->AllowableRace & getRaceMask()) == 0)
            return EQUIP_ERR_CANT_EQUIP_EVER;

        if (proto->RequiredSkill != 0)
        {
            if (GetSkillValue(proto->RequiredSkill) == 0)
                return EQUIP_ERR_PROFICIENCY_NEEDED;
            else if (GetSkillValue(proto->RequiredSkill) < proto->RequiredSkillRank)
                return EQUIP_ERR_CANT_EQUIP_SKILL;
        }

        if (proto->RequiredSpell != 0 && !HasSpell(proto->RequiredSpell))
            return EQUIP_ERR_PROFICIENCY_NEEDED;

        if (getLevel() < proto->RequiredLevel)
            return EQUIP_ERR_CANT_EQUIP_LEVEL_I;

        // If World Event is not active, prevent using event dependant items
        if (proto->HolidayId && !IsHolidayActive((HolidayIds)proto->HolidayId))
            return EQUIP_ERR_CLIENT_LOCKED_OUT;

        return EQUIP_ERR_OK;
    }

    return EQUIP_ERR_ITEM_NOT_FOUND;
}

InventoryResult Player::CanRollForItemInLFG(ItemTemplate const* proto, WorldObject const* lootedObject) const
{
    LfgDungeonSet const& dungeons = sLFGMgr->GetSelectedDungeons(GetGUID());
    if (dungeons.empty())
        return EQUIP_ERR_OK;    // not using LFG

    if (!GetGroup() || !GetGroup()->isLFGGroup())
        return EQUIP_ERR_OK;    // not in LFG group

    // check if looted object is inside the lfg dungeon
    bool lootedObjectInDungeon = false;
    Map const* map = lootedObject->GetMap();
    if (uint32 dungeonId = sLFGMgr->GetDungeon(GetGroup()->GetGUID(), true))
        if (LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(dungeonId))
            if (uint32(dungeon->map) == map->GetId() && dungeon->difficulty == uint32(map->GetDifficultyID()))
                lootedObjectInDungeon = true;

    if (!lootedObjectInDungeon)
        return EQUIP_ERR_OK;

    if (!proto)
        return EQUIP_ERR_ITEM_NOT_FOUND;
   // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player

    const static uint32 item_weapon_skills[MAX_ITEM_SUBCLASS_WEAPON] =
    {
        SKILL_AXES,     SKILL_2H_AXES,  SKILL_BOWS,          SKILL_GUNS,      SKILL_MACES,
        SKILL_2H_MACES, SKILL_POLEARMS, SKILL_SWORDS,        SKILL_2H_SWORDS, 0,
        SKILL_STAVES,   0,              0,                   SKILL_FIST_WEAPONS,   0,
        SKILL_DAGGERS,  SKILL_THROWN,   SKILL_ASSASSINATION, SKILL_CROSSBOWS, SKILL_WANDS,
        SKILL_FISHING
    }; //Copy from function Item::GetSkill()

    if ((proto->AllowableClass & getClassMask()) == 0 || (proto->AllowableRace & getRaceMask()) == 0)
        return EQUIP_ERR_CANT_EQUIP_EVER;

    if (proto->RequiredSpell != 0 && !HasSpell(proto->RequiredSpell))
        return EQUIP_ERR_PROFICIENCY_NEEDED;

    if (proto->RequiredSkill != 0)
    {
        if (!GetSkillValue(proto->RequiredSkill))
            return EQUIP_ERR_PROFICIENCY_NEEDED;
        else if (GetSkillValue(proto->RequiredSkill) < proto->RequiredSkillRank)
            return EQUIP_ERR_CANT_EQUIP_SKILL;
    }

    uint8 _class = getClass();

    if (proto->Class == ITEM_CLASS_WEAPON && GetSkillValue(item_weapon_skills[proto->SubClass]) == 0)
        return EQUIP_ERR_PROFICIENCY_NEEDED;

    if (proto->Class == ITEM_CLASS_ARMOR && proto->SubClass > ITEM_SUBCLASS_ARMOR_MISCELLANEOUS && proto->SubClass < ITEM_SUBCLASS_ARMOR_COSMETIC && proto->InventoryType != INVTYPE_CLOAK)
    {
        if (_class == CLASS_WARRIOR || _class == CLASS_PALADIN || _class == CLASS_DEATH_KNIGHT)
        {
            if (getLevel() < 40)
            {
                if (proto->SubClass != ITEM_SUBCLASS_ARMOR_MAIL)
                    return EQUIP_ERR_CLIENT_LOCKED_OUT;
            }
            else if (proto->SubClass != ITEM_SUBCLASS_ARMOR_PLATE)
                return EQUIP_ERR_CLIENT_LOCKED_OUT;
        }
        else if (_class == CLASS_HUNTER || _class == CLASS_SHAMAN)
        {
            if (getLevel() < 40)
            {
                if (proto->SubClass != ITEM_SUBCLASS_ARMOR_LEATHER)
                    return EQUIP_ERR_CLIENT_LOCKED_OUT;
            }
            else if (proto->SubClass != ITEM_SUBCLASS_ARMOR_MAIL)
                return EQUIP_ERR_CLIENT_LOCKED_OUT;
        }

        if (_class == CLASS_ROGUE || _class == CLASS_DRUID)
            if (proto->SubClass != ITEM_SUBCLASS_ARMOR_LEATHER)
                return EQUIP_ERR_CLIENT_LOCKED_OUT;

        if (_class == CLASS_MAGE || _class == CLASS_PRIEST || _class == CLASS_WARLOCK)
            if (proto->SubClass != ITEM_SUBCLASS_ARMOR_CLOTH)
                return EQUIP_ERR_CLIENT_LOCKED_OUT;
    }

    return EQUIP_ERR_OK;
}

Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update, int32 randomPropertyId)
{
    AllowedLooterSet allowedLooters;
    return StoreNewItem(dest, item, update, randomPropertyId, allowedLooters);
}

// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update, int32 randomPropertyId, AllowedLooterSet& allowedLooters)
{
    uint32 count = 0;
    for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
        count += itr->count;

    Item* pItem = Item::CreateItem(item, count, this);
    if (pItem)
    {
        ItemAddedQuestCheck(item, count);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, count);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, item, 1);
        if (randomPropertyId)
            pItem->SetItemRandomProperties(randomPropertyId);
        pItem = StoreItem(dest, pItem, update);

        if (pItem->GetTemplate()->Quality == ITEM_QUALITY_HEIRLOOM)
            if (HeirloomEntry const* l_HeirloomEntry = GetHeirloomEntryByItemID(pItem->GetTemplate()->ItemId))
                AddHeirloom(l_HeirloomEntry, pItem->HasCustomFlags(ItemCustomFlags::FromStore));

        if (allowedLooters.size() > 1 && pItem->GetTemplate()->GetMaxStackSize() == 1 && pItem->IsSoulBound())
        {
            pItem->SetSoulboundTradeable(allowedLooters);
            pItem->SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, GetTotalPlayedTime());
            AddTradeableItem(pItem);

            // save data
            std::ostringstream ss;
            AllowedLooterSet::const_iterator itr = allowedLooters.begin();
            ss << *itr;
            for (++itr; itr != allowedLooters.end(); ++itr)
                ss << ' ' << *itr;

            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEM_BOP_TRADE);
            stmt->setUInt32(0, pItem->GetGUIDLow());
            stmt->setString(1, ss.str());
            CharacterDatabase.Execute(stmt);
        }
    }
    return pItem;
}

Item* Player::StoreItem(ItemPosCountVec const& dest, Item* pItem, bool update)
{
    if (!pItem)
        return NULL;

    Item* lastItem = pItem;
    for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end();)
    {
        uint16 pos = itr->pos;
        uint32 count = itr->count;

        ++itr;

        if (itr == dest.end())
        {
            lastItem = _StoreItem(pos, pItem, count, false, update);
            break;
        }

        lastItem = _StoreItem(pos, pItem, count, true, update);
    }

    UpdateItemLevel();
    return lastItem;
}

// Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool update)
{
    if (!pItem)
        return NULL;

    uint8 bag = pos >> 8;
    uint8 slot = pos & 255;

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u, guid = %u", bag, slot, pItem->GetEntry(), count, pItem->GetGUIDLow());

    Item* pItem2 = GetItemByPos(bag, slot);
    if (!pItem2)
    {
        if (clone)
            pItem = pItem->CloneItem(count, this);
        else
            pItem->SetCount(count);

        if (!pItem)
            return NULL;

        if (pItem->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP ||
            pItem->GetTemplate()->Bonding == BIND_QUEST_ITEM ||
            (pItem->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
            pItem->SetBinding(true);

        Bag* pBag = (bag == INVENTORY_SLOT_BAG_0) ? NULL : GetBagByPos(bag);
        if (!pBag)
        {
            for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
            {
                if (m_items[i] == pItem)
                {
                    ACE_Stack_Trace trace;
                    sLog->outAshran("VisualizeItem duplicate item ptr ! Try to put item in slot %u already exist in slot %u ! StackTrace : %s", i, slot, trace.c_str());
                }
            }
            m_items[slot] = pItem;
            SetGuidValue(PLAYER_FIELD_INV_SLOTS + (slot * 4), pItem->GetGUID());
            pItem->SetGuidValue(ITEM_FIELD_CONTAINED_IN, GetGUID());
            pItem->SetGuidValue(ITEM_FIELD_OWNER, GetGUID());

            pItem->SetSlot(slot);
            pItem->SetContainer(NULL);
        }
        else
            pBag->StoreItem(slot, pItem, update);

        if (IsInWorld() && update)
        {
            pItem->AddToWorld();
            pItem->SendUpdateToPlayer(this);
        }

        pItem->SetState(ITEM_CHANGED, this);
        if (pBag)
            pBag->SetState(ITEM_CHANGED, this);

        AddEnchantmentDurations(pItem);
        AddItemDurations(pItem);


        const ItemTemplate* proto = pItem->GetTemplate();
        for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
            if (proto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE && proto->Spells[i].SpellId > 0) // On obtain trigger
                if (bag == INVENTORY_SLOT_BAG_0 || (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END))
                    if (!HasAura(proto->Spells[i].SpellId))
                        CastSpell(this, proto->Spells[i].SpellId, true, pItem);

        return pItem;
    }
    else
    {
        if (pItem2->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP ||
            pItem2->GetTemplate()->Bonding == BIND_QUEST_ITEM ||
            (pItem2->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
            pItem2->SetBinding(true);

        pItem2->SetCount(pItem2->GetCount() + count);
        if (IsInWorld() && update)
            pItem2->SendUpdateToPlayer(this);

        if (!clone)
        {
            if (pItem != pItem2)
            {
                // delete item (it not in any slot currently)
                if (IsInWorld() && update)
                {
                    pItem->RemoveFromWorld();
                    pItem->DestroyForPlayer(this);
                }

                RemoveEnchantmentDurations(pItem);
                RemoveItemDurations(pItem);

                pItem->SetOwnerGUID(GetGUID());                 // prevent error at next SetState in case trade/mail/buy from vendor
                pItem->SetNotRefundable(this);
                pItem->ClearSoulboundTradeable(this);
                RemoveTradeableItem(pItem);
                pItem->SetState(ITEM_REMOVED, this);
            }
        }

        AddEnchantmentDurations(pItem2);

        pItem2->SetState(ITEM_CHANGED, this);

        const ItemTemplate* proto = pItem2->GetTemplate();
        for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
            if (proto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE && proto->Spells[i].SpellId > 0) // On obtain trigger
                if (bag == INVENTORY_SLOT_BAG_0 || (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END))
                    if (!HasAura(proto->Spells[i].SpellId))
                        CastSpell(this, proto->Spells[i].SpellId, true, pItem2);

        return pItem2;
    }
}

Item* Player::EquipNewItem(uint16 pos, uint32 item, bool update)
{
    if (Item* pItem = Item::CreateItem(item, 1, this))
    {
        ItemAddedQuestCheck(item, 1);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, item, 1);
        return EquipItem(pos, pItem, update);
    }

    return NULL;
}

Item* Player::EquipItem(uint16 pos, Item* pItem, bool update)
{
    if (pItem->GetTemplate()->Flags3 & ItemFlags3::ITEM_FLAG3_WARGAME_ONLY)
    {
        if (!GetBattleground() || !GetBattleground()->IsWargame())
            pItem->SetFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE);
    }
    else if (GetBattleground() && GetBattleground()->UseTournamentRules())
        pItem->SetFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE);

    AddEnchantmentDurations(pItem);
    AddItemDurations(pItem);

    uint8 bag = pos >> 8;
    uint8 slot = pos & 255;

    Item* pItem2 = GetItemByPos(bag, slot);

    if (!pItem2)
    {
        VisualizeItem(slot, pItem);

        if (isAlive())
        {
            ItemTemplate const* pProto = pItem->GetTemplate();

            // item set bonuses applied only at equip and removed at unequip, and still active for broken items
            if (pProto && pProto->ItemSet)
                AddItemsSetItem(this, pItem);

            _ApplyItemMods(pItem, slot, true);

            if (pProto && isInCombat() && (pProto->Class == ITEM_CLASS_WEAPON || pProto->InventoryType == INVTYPE_RELIC) && m_weaponChangeTimer == 0)
            {
                uint32 cooldownSpell = getClass() == CLASS_ROGUE ? 6123 : 6119;
                SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(cooldownSpell);

                if (!spellProto)
                    sLog->outError(LOG_FILTER_PLAYER, "Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
                else
                {
                    m_weaponChangeTimer = spellProto->StartRecoveryTime;

                    GetGlobalCooldownMgr().AddGlobalCooldown(spellProto, m_weaponChangeTimer);

                    WorldPacket data(SMSG_SPELL_COOLDOWN, 16 + 2 + 1 + 4 + 4 + 4);
                    data.appendPackGUID(GetGUID());
                    data << uint8(CooldownFlags::CooldownFlagIncludeGCD);
                    data << uint32(1);
                    data << uint32(cooldownSpell);
                    data << uint32(0);

                    GetSession()->SendPacket(&data);
                }
            }
        }

        if (IsInWorld() && update)
        {
            pItem->AddToWorld();
            pItem->SendUpdateToPlayer(this);
        }

        ApplyEquipCooldown(pItem);
    }
    else
    {
        pItem2->SetCount(pItem2->GetCount() + pItem->GetCount());
        if (IsInWorld() && update)
            pItem2->SendUpdateToPlayer(this);

        // delete item (it not in any slot currently)
        //pItem->DeleteFromDB();
        if (IsInWorld() && update)
        {
            pItem->RemoveFromWorld();
            pItem->DestroyForPlayer(this);
        }

        RemoveEnchantmentDurations(pItem);
        RemoveItemDurations(pItem);

        pItem->SetOwnerGUID(GetGUID());                     // prevent error at next SetState in case trade/mail/buy from vendor
        pItem->SetNotRefundable(this);
        pItem->ClearSoulboundTradeable(this);
        RemoveTradeableItem(pItem);
        pItem->SetState(ITEM_REMOVED, this);
        pItem2->SetState(ITEM_CHANGED, this);

        ApplyEquipCooldown(pItem2);

        return pItem2;
    }

    // only for full equip instead adding to stack
    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, pItem->GetEntry(), slot);

    // Custom MoP script
    // Jab Override Driver
    if (getClass() == CLASS_MONK)
    {
        Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);

        // Glyph of Jab
        if (mainItem && mainItem->GetTemplate()->Class == ITEM_CLASS_WEAPON && !HasAura(125660))
        {
            RemoveAura(108561); // 2H Staff Override
            RemoveAura(115697); // 2H Polearm Override
            RemoveAura(115689); // D/W Axes// Way of the Monk - 120277
            RemoveAura(115694); // D/W Maces
            RemoveAura(115696); // D/W Swords

            switch (mainItem->GetTemplate()->SubClass)
            {
                case ITEM_SUBCLASS_WEAPON_STAFF:
                    CastSpell(this, 108561, true);
                    break;
                case ITEM_SUBCLASS_WEAPON_POLEARM:
                    CastSpell(this, 115697, true);
                    break;
                case ITEM_SUBCLASS_WEAPON_AXE:
                    CastSpell(this, 115689, true);
                    break;
                case ITEM_SUBCLASS_WEAPON_MACE:
                    CastSpell(this, 115694, true);
                    break;
                case ITEM_SUBCLASS_WEAPON_SWORD:
                    CastSpell(this, 115696, true);
                    break;
                default:
                    break;
            }
        }
        else if (HasAura(125660))
        {
            RemoveAura(108561); // 2H Staff Override
            RemoveAura(115697); // 2H Polearm Override
            RemoveAura(115689); // D/W Axes
            RemoveAura(115694); // D/W Maces
            RemoveAura(115696); // D/W Swords
        }
    }
    // Way of the Monk - 120277
    if (getClass() == CLASS_MONK && HasAura(120277))
    {
        RemoveAurasDueToSpell(120275);
        RemoveAurasDueToSpell(108977);

        uint32 trigger = 0;
        if (IsTwoHandUsed())
            trigger = 120275;
        else
        {
            Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
            Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
            if (mainItem && mainItem->GetTemplate()->Class == ITEM_CLASS_WEAPON && offItem && offItem->GetTemplate()->Class == ITEM_CLASS_WEAPON)
                trigger = 108977;
        }

        if (trigger)
            CastSpell(this, trigger, true);

        UpdateRating(CR_HASTE_MELEE);
    }
    // Assassin's Resolve - 84601
    if (getClass() == CLASS_ROGUE && GetSpecializationId() == SPEC_ROGUE_ASSASSINATION)
    {
        Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
        Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);

        if (((mainItem && mainItem->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER) || (offItem && offItem->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER)))
        {
            if (HasAura(84601))
                RemoveAura(84601);

            CastSpell(this, 84601, true);
        }
        else
            RemoveAura(84601);
    }
    /// Single-Minded Fury - 81099
    if (getClass() == CLASS_WARRIOR && GetSpecializationId() == SPEC_WARRIOR_FURY)
    {
        if (HasAura(81099))
        {
            RemoveAura(81099);
            AddAura(81099, this);
        }
        if (HasAura(23588))
        {
            RemoveAura(23588);
            AddAura(23588, this);
        }
    }

    // close gossips
    PlayerTalkClass->ClearMenus();
    PlayerTalkClass->SendCloseGossip();
    UpdateItemLevel();

    return pItem;
}

void Player::QuickEquipItem(uint16 pos, Item* pItem)
{
    if (pItem)
    {
        AddEnchantmentDurations(pItem);
        AddItemDurations(pItem);

        uint8 slot = pos & 255;
        VisualizeItem(slot, pItem);

        if (IsInWorld())
        {
            pItem->AddToWorld();
            pItem->SendUpdateToPlayer(this);
        }

        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM, pItem->GetEntry(), slot);
    }
}

void Player::SetVisibleItemSlot(uint8 slot, Item* pItem)
{
    if (pItem)
    {
        SetUInt32Value(PLAYER_FIELD_VISIBLE_ITEMS + (slot * 2) + 0, pItem->GetVisibleEntry());
        SetUInt16Value(PLAYER_FIELD_VISIBLE_ITEMS + (slot * 2) + 1, 0, pItem->GetAppearanceModID());
        SetUInt16Value(PLAYER_FIELD_VISIBLE_ITEMS + (slot * 2) + 1, 1, pItem->GetEnchantItemVisualId(PERM_ENCHANTMENT_SLOT));
    }
    else
    {
        SetUInt32Value(PLAYER_FIELD_VISIBLE_ITEMS + (slot * 2) + 0, 0);
        SetUInt32Value(PLAYER_FIELD_VISIBLE_ITEMS + (slot * 2) + 1, 0);
    }
}

void Player::VisualizeItem(uint8 slot, Item* pItem)
{
    if (!pItem)
        return;

    // check also  BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
    if (pItem->GetTemplate()->Bonding == BIND_WHEN_EQUIPED || pItem->GetTemplate()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetTemplate()->Bonding == BIND_QUEST_ITEM)
        pItem->SetBinding(true);

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());

    for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
    {
        if (m_items[i] == pItem)
        {
            ACE_Stack_Trace trace;
            sLog->outAshran("VisualizeItem duplicate item ptr ! Try to put item in slot %u already exist in slot %u ! StackTrace : %s", i, slot, trace.c_str());
        }
    }

    m_items[slot] = pItem;
    SetGuidValue(PLAYER_FIELD_INV_SLOTS + (slot * 4), pItem->GetGUID());
    pItem->SetGuidValue(ITEM_FIELD_CONTAINED_IN, GetGUID());
    pItem->SetGuidValue(ITEM_FIELD_OWNER, GetGUID());
    pItem->SetSlot(slot);
    pItem->SetContainer(NULL);

    if (slot < EQUIPMENT_SLOT_END)
        SetVisibleItemSlot(slot, pItem);

    pItem->SetState(ITEM_CHANGED, this);
}

void Player::RemoveItem(uint8 bag, uint8 slot, bool update)
{
    // note: removeitem does not actually change the item
    // it only takes the item out of storage temporarily
    // note2: if removeitem is to be used for delinking
    // the item must be removed from the player's updatequeue

    Item* pItem = GetItemByPos(bag, slot);
    if (pItem)
    {
        sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());

        RemoveEnchantmentDurations(pItem);
        RemoveItemDurations(pItem);
        RemoveTradeableItem(pItem);

        if (bag == INVENTORY_SLOT_BAG_0)
        {
            if (slot < INVENTORY_SLOT_BAG_END)
            {
                ItemTemplate const* pProto = pItem->GetTemplate();
                // item set bonuses applied only at equip and removed at unequip, and still active for broken items

                if (pProto && pProto->ItemSet)
                    RemoveItemsSetItem(this, pProto);

                _ApplyItemMods(pItem, slot, false);

                // remove item dependent auras and casts (only weapon and armor slots)
                if (slot < EQUIPMENT_SLOT_END)
                {
                    RemoveItemDependentAurasAndCasts(pItem);

                    // remove held enchantments
                    if (slot == EQUIPMENT_SLOT_MAINHAND)
                    {
                        if (pItem->GetItemSuffixFactor())
                        {
                            pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
                            pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
                        }
                        else
                        {
                            pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
                            pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
                        }
                    }
                }
            }

            m_items[slot] = NULL;
            SetGuidValue(PLAYER_FIELD_INV_SLOTS + (slot * 4), 0);

            if (slot < EQUIPMENT_SLOT_END)
                SetVisibleItemSlot(slot, NULL);
        }
        else if (Bag* pBag = GetBagByPos(bag))
            pBag->RemoveItem(slot, update);

        pItem->SetGuidValue(ITEM_FIELD_CONTAINED_IN, 0);
        pItem->SetSlot(NULL_SLOT);
        if (IsInWorld() && update)
            pItem->SendUpdateToPlayer(this);
    }
    UpdateItemLevel();
}

// Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
{
    if (Item* it = GetItemByPos(bag, slot))
    {
        ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
        RemoveItem(bag, slot, update);
        it->SetNotRefundable(this, false);
        it->RemoveFromUpdateQueueOf(this);
        if (it->IsInWorld())
        {
            it->RemoveFromWorld();
            it->DestroyForPlayer(this);
        }
    }
}

// Common operation need to add item from inventory without delete in trade, guild bank, mail....
void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
{
    // update quest counters
    ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount());

    // store item
    Item* pLastItem = StoreItem(dest, pItem, update);

    // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
    if (pLastItem == pItem)
    {
        // update owner for last item (this can be original item with wrong owner
        if (pLastItem->GetOwnerGUID() != GetGUID())
            pLastItem->SetOwnerGUID(GetGUID());

        // if this original item then it need create record in inventory
        // in case trade we already have item in other player inventory
        pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
    }

    if (pLastItem->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE))
        AddTradeableItem(pLastItem);
}

void Player::DestroyItem(uint8 bag, uint8 slot, bool update)
{
    Item* pItem = GetItemByPos(bag, slot);
    if (pItem)
    {
        sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
        sScriptMgr->OnItemDestroyed(this, pItem);

        // Also remove all contained items if the item is a bag.
        // This if () prevents item saving crashes if the condition for a bag to be empty before being destroyed was bypassed somehow.
        if (pItem->IsNotEmptyBag())
            for (uint8 i = 0; i < MAX_BAG_SIZE; ++i)
                DestroyItem(slot, i, update);

        if (pItem->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_WRAPPED))
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT);

            stmt->setUInt32(0, pItem->GetGUIDLow());

            CharacterDatabase.Execute(stmt);
        }

        RemoveEnchantmentDurations(pItem);
        RemoveItemDurations(pItem);

        pItem->SetNotRefundable(this);
        pItem->ClearSoulboundTradeable(this);
        RemoveTradeableItem(pItem);

        const ItemTemplate* proto = pItem->GetTemplate();
        for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
            if (proto->Spells[i].SpellTrigger == ITEM_SPELLTRIGGER_ON_NO_DELAY_USE && proto->Spells[i].SpellId > 0) // On obtain trigger
                RemoveAurasDueToSpell(proto->Spells[i].SpellId);

        ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount());

        if (bag == INVENTORY_SLOT_BAG_0)
        {
            SetGuidValue(PLAYER_FIELD_INV_SLOTS + (slot * 4), 0);

            // equipment and equipped bags can have applied bonuses
            if (slot < INVENTORY_SLOT_BAG_END)
            {
                ItemTemplate const* pProto = pItem->GetTemplate();

                // item set bonuses applied only at equip and removed at unequip, and still active for broken items
                if (pProto && pProto->ItemSet)
                    RemoveItemsSetItem(this, pProto);

                _ApplyItemMods(pItem, slot, false);
            }

            if (slot < EQUIPMENT_SLOT_END)
            {
                // remove item dependent auras and casts (only weapon and armor slots)
                RemoveItemDependentAurasAndCasts(pItem);

                // equipment visual show
                SetVisibleItemSlot(slot, NULL);
            }

            m_items[slot] = NULL;
        }
        else if (Bag* pBag = GetBagByPos(bag))
            pBag->RemoveItem(slot, update);

        if (IsInWorld() && update)
        {
            pItem->RemoveFromWorld();
            pItem->DestroyForPlayer(this);
        }

        //pItem->SetOwnerGUID(0);
        pItem->SetGuidValue(ITEM_FIELD_CONTAINED_IN, 0);
        pItem->SetSlot(NULL_SLOT);
        pItem->SetState(ITEM_REMOVED, this);
    }
}

void Player::DestroyItemCount(uint32 item, uint32 count, bool update, bool unequip_check)
{
    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
    uint32 remcount = 0;

    // in inventory
    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
    {
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
        {
            if (pItem->GetEntry() == item && !pItem->IsInTrade())
            {
                if (pItem->GetCount() + remcount <= count)
                {
                    // all items in inventory can unequipped
                    remcount += pItem->GetCount();
                    DestroyItem(INVENTORY_SLOT_BAG_0, i, update);

                    if (remcount >= count)
                        return;
                }
                else
                {
                    ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
                    pItem->SetCount(pItem->GetCount() - count + remcount);
                    if (IsInWorld() && update)
                        pItem->SendUpdateToPlayer(this);
                    pItem->SetState(ITEM_CHANGED, this);
                    return;
                }
            }
        }
    }

    // in inventory bags
    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        if (Bag* pBag = GetBagByPos(i))
        {
            for (uint32 j = 0; j < pBag->GetBagSize(); j++)
            {
                if (Item* pItem = pBag->GetItemByPos(j))
                {
                    if (pItem->GetEntry() == item && !pItem->IsInTrade())
                    {
                        // all items in bags can be unequipped
                        if (pItem->GetCount() + remcount <= count)
                        {
                            remcount += pItem->GetCount();
                            DestroyItem(i, j, update);

                            if (remcount >= count)
                                return;
                        }
                        else
                        {
                            ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
                            pItem->SetCount(pItem->GetCount() - count + remcount);
                            if (IsInWorld() && update)
                                pItem->SendUpdateToPlayer(this);
                            pItem->SetState(ITEM_CHANGED, this);
                            return;
                        }
                    }
                }
            }
        }
    }

    // in equipment and bag list
    for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
    {
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
        {
            if (pItem && pItem->GetEntry() == item && !pItem->IsInTrade())
            {
                if (pItem->GetCount() + remcount <= count)
                {
                    if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK)
                    {
                        remcount += pItem->GetCount();
                        DestroyItem(INVENTORY_SLOT_BAG_0, i, update);

                        if (remcount >= count)
                            return;
                    }
                }
                else
                {
                    ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
                    pItem->SetCount(pItem->GetCount() - count + remcount);
                    if (IsInWorld() && update)
                        pItem->SendUpdateToPlayer(this);
                    pItem->SetState(ITEM_CHANGED, this);
                    return;
                }
            }
        }
    }

    // in bank
    for (uint8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
    {
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
        {
            if (pItem->GetEntry() == item && !pItem->IsInTrade())
            {
                if (pItem->GetCount() + remcount <= count)
                {
                    remcount += pItem->GetCount();
                    DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
                    if (remcount >= count)
                        return;
                }
                else
                {
                    ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
                    pItem->SetCount(pItem->GetCount() - count + remcount);
                    if (IsInWorld() && update)
                        pItem->SendUpdateToPlayer(this);
                    pItem->SetState(ITEM_CHANGED, this);
                    return;
                }
            }
        }
    }

    // in regeant bank
    for (uint8 i = REAGENT_BANK_SLOT_BAG_START; i < REAGENT_BANK_SLOT_BAG_END; i++)
    {
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
        {
            if (pItem->GetEntry() == item && !pItem->IsInTrade())
            {
                if (pItem->GetCount() + remcount <= count)
                {
                    remcount += pItem->GetCount();
                    DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
                    if (remcount >= count)
                        return;
                }
                else
                {
                    ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
                    pItem->SetCount(pItem->GetCount() - count + remcount);
                    if (IsInWorld() && update)
                        pItem->SendUpdateToPlayer(this);
                    pItem->SetState(ITEM_CHANGED, this);
                    return;
                }
            }
        }
    }

    // in bank bags
    for (uint8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
    {
        if (Bag* pBag = GetBagByPos(i))
        {
            for (uint32 j = 0; j < pBag->GetBagSize(); j++)
            {
                if (Item* pItem = pBag->GetItemByPos(j))
                {
                    if (pItem->GetEntry() == item && !pItem->IsInTrade())
                    {
                        // all items in bags can be unequipped
                        if (pItem->GetCount() + remcount <= count)
                        {
                            remcount += pItem->GetCount();
                            DestroyItem(i, j, update);

                            if (remcount >= count)
                                return;
                        }
                        else
                        {
                            ItemRemovedQuestCheck(pItem->GetEntry(), count - remcount);
                            pItem->SetCount(pItem->GetCount() - count + remcount);
                            if (IsInWorld() && update)
                                pItem->SendUpdateToPlayer(this);
                            pItem->SetState(ITEM_CHANGED, this);
                            return;
                        }
                    }
                }
            }
        }
    }
}

void Player::DestroyZoneLimitedItem(bool update, uint32 new_zone)
{
    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone);

    // in inventory
    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
                DestroyItem(INVENTORY_SLOT_BAG_0, i, update);

    // in inventory bags
    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
        if (Bag* pBag = GetBagByPos(i))
            for (uint32 j = 0; j < pBag->GetBagSize(); j++)
                if (Item* pItem = pBag->GetItemByPos(j))
                    if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
                        DestroyItem(i, j, update);

    // in equipment and bag list
    for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
                DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
}

void Player::DestroyConjuredItems(bool update)
{
    // used when entering arena
    // destroys all conjured items
    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyConjuredItems");

    // in inventory
    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->IsConjuredConsumable())
                DestroyItem(INVENTORY_SLOT_BAG_0, i, update);

    // in inventory bags
    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
        if (Bag* pBag = GetBagByPos(i))
            for (uint32 j = 0; j < pBag->GetBagSize(); j++)
                if (Item* pItem = pBag->GetItemByPos(j))
                    if (pItem->IsConjuredConsumable())
                        DestroyItem(i, j, update);

    // in equipment and bag list
    for (uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->IsConjuredConsumable())
                DestroyItem(INVENTORY_SLOT_BAG_0, i, update);
}

Item* Player::GetItemByEntry(uint32 entry) const
{
    // in inventory
    for (int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->GetEntry() == entry)
                return pItem;

    for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
        if (Bag* pBag = GetBagByPos(i))
            for (uint32 j = 0; j < pBag->GetBagSize(); ++j)
                if (Item* pItem = pBag->GetItemByPos(j))
                    if (pItem->GetEntry() == entry)
                        return pItem;

    for (int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->GetEntry() == entry)
                return pItem;

    return NULL;
}

void Player::DestroyItemCount(Item* pItem, uint32 &count, bool update)
{
    if (!pItem)
        return;

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(), pItem->GetEntry(), count);

    if (pItem->GetCount() <= count)
    {
        count -= pItem->GetCount();

        DestroyItem(pItem->GetBagSlot(), pItem->GetSlot(), update);
    }
    else
    {
        ItemRemovedQuestCheck(pItem->GetEntry(), count);
        pItem->SetCount(pItem->GetCount() - count);
        count = 0;
        if (IsInWorld() && update)
            pItem->SendUpdateToPlayer(this);
        pItem->SetState(ITEM_CHANGED, this);
    }
}

void Player::SplitItem(uint16 src, uint16 dst, uint32 count)
{
    uint8 srcbag = src >> 8;
    uint8 srcslot = src & 255;

    uint8 dstbag = dst >> 8;
    uint8 dstslot = dst & 255;

    Item* pSrcItem = GetItemByPos(srcbag, srcslot);
    if (!pSrcItem)
    {
        SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL);
        return;
    }

    if (pSrcItem->m_lootGenerated)                           // prevent split looting item (item
    {
        //best error message found for attempting to split while looting
        SendEquipError(EQUIP_ERR_SPLIT_FAILED, pSrcItem, NULL);
        return;
    }

    // not let split all items (can be only at cheating)
    if (pSrcItem->GetCount() == count)
    {
        SendEquipError(EQUIP_ERR_SPLIT_FAILED, pSrcItem, NULL);
        return;
    }

    // not let split more existed items (can be only at cheating)
    if (pSrcItem->GetCount() < count)
    {
        SendEquipError(EQUIP_ERR_TOO_FEW_TO_SPLIT, pSrcItem, NULL);
        return;
    }

    //! If trading
    if (TradeData* tradeData = GetTradeData())
    {
        //! If current item is in trade window (only possible with packet spoofing - silent return)
        if (tradeData->GetTradeSlotForItem(pSrcItem->GetGUID()) != TRADE_SLOT_INVALID)
            return;
    }

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
    Item* pNewItem = pSrcItem->CloneItem(count, this);
    if (!pNewItem)
    {
        SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL);
        return;
    }

    if (IsInventoryPos(dst))
    {
        // change item amount before check (for unique max count check)
        pSrcItem->SetCount(pSrcItem->GetCount() - count);

        ItemPosCountVec dest;
        InventoryResult msg = CanStoreItem(dstbag, dstslot, dest, pNewItem, false);
        if (msg != EQUIP_ERR_OK)
        {
            delete pNewItem;
            pSrcItem->SetCount(pSrcItem->GetCount() + count);
            SendEquipError(msg, pSrcItem, NULL);
            return;
        }

        if (IsInWorld())
            pSrcItem->SendUpdateToPlayer(this);
        pSrcItem->SetState(ITEM_CHANGED, this);
        StoreItem(dest, pNewItem, true);
    }
    else if (IsBankPos(dst))
    {
        // change item amount before check (for unique max count check)
        pSrcItem->SetCount(pSrcItem->GetCount() - count);

        ItemPosCountVec dest;
        InventoryResult msg = CanBankItem(dstbag, dstslot, dest, pNewItem, false);
        if (msg != EQUIP_ERR_OK)
        {
            delete pNewItem;
            pSrcItem->SetCount(pSrcItem->GetCount() + count);
            SendEquipError(msg, pSrcItem, NULL);
            return;
        }

        if (IsInWorld())
            pSrcItem->SendUpdateToPlayer(this);
        pSrcItem->SetState(ITEM_CHANGED, this);
        BankItem(dest, pNewItem, true);
    }
    else if (IsEquipmentPos(dst))
    {
        // change item amount before check (for unique max count check), provide space for splitted items
        pSrcItem->SetCount(pSrcItem->GetCount() - count);

        uint16 dest;
        InventoryResult msg = CanEquipItem(dstslot, dest, pNewItem, false);
        if (msg != EQUIP_ERR_OK)
        {
            delete pNewItem;
            pSrcItem->SetCount(pSrcItem->GetCount() + count);
            SendEquipError(msg, pSrcItem, NULL);
            return;
        }

        if (IsInWorld())
            pSrcItem->SendUpdateToPlayer(this);
        pSrcItem->SetState(ITEM_CHANGED, this);
        EquipItem(dest, pNewItem, true);
        AutoUnequipOffhandIfNeed();
    }
}

void Player::SwapItem(uint16 src, uint16 dst)
{
    uint8 srcbag = src >> 8;
    uint8 srcslot = src & 255;

    uint8 dstbag = dst >> 8;
    uint8 dstslot = dst & 255;

    Item* pSrcItem = GetItemByPos(srcbag, srcslot);
    Item* pDstItem = GetItemByPos(dstbag, dstslot);

    /// If we want to swap the same item it is useless.
    if (pSrcItem == pDstItem)
        return;

    if (!pSrcItem)
        return;

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());

    if (!isAlive())
    {
        SendEquipError(EQUIP_ERR_PLAYER_DEAD, pSrcItem, pDstItem);
        return;
    }

    // close gossips
    PlayerTalkClass->ClearMenus();
    PlayerTalkClass->SendCloseGossip();

    // SRC checks

    if (pSrcItem->m_lootGenerated)                           // prevent swap looting item
    {
        //best error message found for attempting to swap while looting
        SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, pSrcItem, NULL);
        return;
    }

    // check unequip potability for equipped items and bank bags
    if (IsEquipmentPos(src) || IsBagPos(src))
    {
        // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
        InventoryResult msg = CanUnequipItem(src, !IsBagPos(src) || IsBagPos(dst) || (pDstItem && pDstItem->ToBag() && pDstItem->ToBag()->IsEmpty()));
        if (msg != EQUIP_ERR_OK)
        {
            SendEquipError(msg, pSrcItem, pDstItem);
            return;
        }
    }

    // prevent put equipped/bank bag in self
    if (IsBagPos(src) && srcslot == dstbag)
    {
        SendEquipError(EQUIP_ERR_BAG_IN_BAG, pSrcItem, pDstItem);
        return;
    }

    // prevent equipping bag in the same slot from its inside
    if (IsBagPos(dst) && srcbag == dstslot)
    {
        SendEquipError(EQUIP_ERR_CANT_SWAP, pSrcItem, pDstItem);
        return;
    }

    //! If trading
    if (TradeData* tradeData = GetTradeData())
    {
        //! If current item is in trade window (only possible with packet spoofing - silent return)
        if (tradeData->GetTradeSlotForItem(pSrcItem->GetGUID()) != TRADE_SLOT_INVALID)
            TradeCancel(true);
    }

    // DST checks

    if (pDstItem)
    {
        if (pDstItem->m_lootGenerated)                       // prevent swap looting item
        {
            //best error message found for attempting to swap while looting
            SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, pDstItem, NULL);
            return;
        }

        // check unequip potability for equipped items and bank bags
        if (IsEquipmentPos(dst) || IsBagPos(dst))
        {
            // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
            InventoryResult msg = CanUnequipItem(dst, !IsBagPos(dst) || IsBagPos(src) || (pSrcItem->ToBag() && pSrcItem->ToBag()->IsEmpty()));
            if (msg != EQUIP_ERR_OK)
            {
                SendEquipError(msg, pSrcItem, pDstItem);
                return;
            }
        }
    }

    // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
    // or swap empty bag with another empty or not empty bag (with items exchange)

    // Move case
    if (!pDstItem)
    {
        if (IsInventoryPos(dst))
        {
            ItemPosCountVec dest;
            InventoryResult msg = CanStoreItem(dstbag, dstslot, dest, pSrcItem, false);
            if (msg != EQUIP_ERR_OK)
            {
                SendEquipError(msg, pSrcItem, NULL);
                return;
            }
            RemoveItem(srcbag, srcslot, true);
            StoreItem(dest, pSrcItem, true);
            if (IsBankPos(src))
                ItemAddedQuestCheck(pSrcItem->GetEntry(), pSrcItem->GetCount());
        }
        else if (IsBankPos(dst))
        {
            ItemPosCountVec dest;
            InventoryResult msg = CanBankItem(dstbag, dstslot, dest, pSrcItem, false);
            if (msg != EQUIP_ERR_OK)
            {
                SendEquipError(msg, pSrcItem, NULL);
                return;
            }

            RemoveItem(srcbag, srcslot, true);
            BankItem(dest, pSrcItem, true);
            ItemRemovedQuestCheck(pSrcItem->GetEntry(), pSrcItem->GetCount());
        }
        else if (IsReagentBankPos(dst))
        {
            ItemPosCountVec dest;
            InventoryResult msg = CanReagentBankItem(dstbag, dstslot, dest, pSrcItem, false);
            if (msg != EQUIP_ERR_OK)
            {
                SendEquipError(msg, pSrcItem, NULL);
                return;
            }

            RemoveItem(srcbag, srcslot, true);
            BankItem(dest, pSrcItem, true);
            ItemRemovedQuestCheck(pSrcItem->GetEntry(), pSrcItem->GetCount());
        }
        else if (IsEquipmentPos(dst))
        {
            if (pSrcItem->ToBag() && GetTrader())
            {
                SendEquipError(EQUIP_ERR_CANT_SWAP, pSrcItem, NULL);
                return;
            }

            uint16 dest;
            InventoryResult msg = CanEquipItem(dstslot, dest, pSrcItem, false);
            if (msg != EQUIP_ERR_OK)
            {
                SendEquipError(msg, pSrcItem, NULL);
                return;
            }
            RemoveItem(srcbag, srcslot, true);
            EquipItem(dest, pSrcItem, true);
            AutoUnequipOffhandIfNeed();
        }

        // Custom MoP script
        // Jab Override Driver
        if (getClass() == CLASS_MONK)
        {
            Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);

            if (mainItem && mainItem->GetTemplate()->Class == ITEM_CLASS_WEAPON && !HasAura(125660))
            {
                RemoveAura(108561); // 2H Staff Override
                RemoveAura(115697); // 2H Polearm Override
                RemoveAura(115689); // D/W Axes
                RemoveAura(115694); // D/W Maces
                RemoveAura(115696); // D/W Swords

                switch (mainItem->GetTemplate()->SubClass)
                {
                    case ITEM_SUBCLASS_WEAPON_STAFF:
                        CastSpell(this, 108561, true);
                        break;
                    case ITEM_SUBCLASS_WEAPON_POLEARM:
                        CastSpell(this, 115697, true);
                        break;
                    case ITEM_SUBCLASS_WEAPON_AXE:
                        CastSpell(this, 115689, true);
                        break;
                    case ITEM_SUBCLASS_WEAPON_MACE:
                        CastSpell(this, 115694, true);
                        break;
                    case ITEM_SUBCLASS_WEAPON_SWORD:
                        CastSpell(this, 115696, true);
                        break;
                    default:
                        break;
                }
            }
            else
            {
                RemoveAura(108561); // 2H Staff Override
                RemoveAura(115697); // 2H Polearm Override
                RemoveAura(115689); // D/W Axes
                RemoveAura(115694); // D/W Maces
                RemoveAura(115696); // D/W Swords
            }
        }
        // Way of the Monk - 120277
        if (getClass() == CLASS_MONK && HasAura(120277))
        {
            RemoveAurasDueToSpell(120275);
            RemoveAurasDueToSpell(108977);

            uint32 trigger = 0;
            if (IsTwoHandUsed())
                trigger = 120275;
            else
            {
                Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
                Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
                if (mainItem && mainItem->GetTemplate()->Class == ITEM_CLASS_WEAPON && offItem && offItem->GetTemplate()->Class == ITEM_CLASS_WEAPON)
                    trigger = 108977;
            }

            if (trigger)
                CastSpell(this, trigger, true);

            UpdateRating(CR_HASTE_MELEE);
        }
        // Assassin's Resolve - 84601
        if (getClass() == CLASS_ROGUE && GetSpecializationId() == SPEC_ROGUE_ASSASSINATION)
        {
            Item* mainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
            Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);

            if (((mainItem && mainItem->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER) || (offItem && offItem->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER)))
            {
                if (HasAura(84601))
                    RemoveAura(84601);

                CastSpell(this, 84601, true);
            }
            else
                RemoveAura(84601);
        }

        return;
    }

    // attempt merge to / fill target item
    if (!pSrcItem->IsBag() && !pDstItem->IsBag())
    {
        InventoryResult msg;
        ItemPosCountVec sDest;
        uint16 eDest = 0;
        if (IsInventoryPos(dst))
            msg = CanStoreItem(dstbag, dstslot, sDest, pSrcItem, false);
        else if (IsBankPos(dst))
            msg = CanBankItem(dstbag, dstslot, sDest, pSrcItem, false);
        else if (IsReagentBankPos(dst))
            msg = CanReagentBankItem(dstbag, dstslot, sDest, pSrcItem, false);
        else if (IsEquipmentPos(dst))
            msg = CanEquipItem(dstslot, eDest, pSrcItem, false);
        else
            return;

        // can be merge/fill
        if (msg == EQUIP_ERR_OK)
        {
            if (pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetTemplate()->GetMaxStackSize())
            {
                RemoveItem(srcbag, srcslot, true);

                if (IsInventoryPos(dst))
                    StoreItem(sDest, pSrcItem, true);
                else if (IsBankPos(dst))
                    BankItem(sDest, pSrcItem, true);
                else if (IsReagentBankPos(dst))
                    BankItem(sDest, pSrcItem, true);
                else if (IsEquipmentPos(dst))
                {
                    EquipItem(eDest, pSrcItem, true);
                    AutoUnequipOffhandIfNeed();
                }
            }
            else
            {
                pSrcItem->SetCount(pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetTemplate()->GetMaxStackSize());
                pDstItem->SetCount(pSrcItem->GetTemplate()->GetMaxStackSize());
                pSrcItem->SetState(ITEM_CHANGED, this);
                pDstItem->SetState(ITEM_CHANGED, this);
                if (IsInWorld())
                {
                    pSrcItem->SendUpdateToPlayer(this);
                    pDstItem->SendUpdateToPlayer(this);
                }
            }
            SendRefundInfo(pDstItem);
            return;
        }
    }

    // impossible merge/fill, do real swap
    InventoryResult msg = EQUIP_ERR_OK;

    // check src->dest move possibility
    ItemPosCountVec sDest;
    uint16 eDest = 0;
    if (IsInventoryPos(dst))
        msg = CanStoreItem(dstbag, dstslot, sDest, pSrcItem, true);
    else if (IsBankPos(dst))
        msg = CanBankItem(dstbag, dstslot, sDest, pSrcItem, true);
    else if (IsReagentBankPos(dst))
        msg = CanReagentBankItem(dstbag, dstslot, sDest, pSrcItem, true);
    else if (IsEquipmentPos(dst))
    {
        msg = CanEquipItem(dstslot, eDest, pSrcItem, true);
        if (msg == EQUIP_ERR_OK)
            msg = CanUnequipItem(eDest, true);
    }

    if (msg != EQUIP_ERR_OK)
    {
        SendEquipError(msg, pSrcItem, pDstItem);
        return;
    }

    // check dest->src move possibility
    ItemPosCountVec sDest2;
    uint16 eDest2 = 0;
    if (IsInventoryPos(src))
        msg = CanStoreItem(srcbag, srcslot, sDest2, pDstItem, true);
    else if (IsBankPos(src))
        msg = CanBankItem(srcbag, srcslot, sDest2, pDstItem, true);
    else if (IsReagentBankPos(src))
        msg = CanReagentBankItem(srcbag, srcslot, sDest2, pDstItem, true);
    else if (IsEquipmentPos(src))
    {
        msg = CanEquipItem(srcslot, eDest2, pDstItem, true);
        if (msg == EQUIP_ERR_OK)
            msg = CanUnequipItem(eDest2, true);
    }

    if (msg != EQUIP_ERR_OK)
    {
        SendEquipError(msg, pDstItem, pSrcItem);
        return;
    }

    // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
    if (Bag* srcBag = pSrcItem->ToBag())
    {
        if (Bag* dstBag = pDstItem->ToBag())
        {
            if (GetTrader())
            {
                SendEquipError(EQUIP_ERR_CANT_SWAP, pSrcItem, pDstItem);
                return;
            }

            Bag* emptyBag = NULL;
            Bag* fullBag = NULL;
            if (srcBag->IsEmpty() && !IsBagPos(src))
            {
                emptyBag = srcBag;
                fullBag  = dstBag;
            }
            else if (dstBag->IsEmpty() && !IsBagPos(dst))
            {
                emptyBag = dstBag;
                fullBag  = srcBag;
            }

            // bag swap (with items exchange) case
            if (emptyBag && fullBag)
            {
                ItemTemplate const* emptyProto = emptyBag->GetTemplate();

                uint32 count = 0;

                for (uint32 i=0; i < fullBag->GetBagSize(); ++i)
                {
                    Item* bagItem = fullBag->GetItemByPos(i);
                    if (!bagItem)
                        continue;

                    ItemTemplate const* bagItemProto = bagItem->GetTemplate();
                    if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emptyProto))
                    {
                        // one from items not go to empty target bag
                        SendEquipError(EQUIP_ERR_BAG_IN_BAG, pSrcItem, pDstItem);
                        return;
                    }

                    ++count;
                }

                if (count > emptyBag->GetBagSize())
                {
                    // too small targeted bag
                    SendEquipError(EQUIP_ERR_CANT_SWAP, pSrcItem, pDstItem);
                    return;
                }

                // Items swap
                count = 0;                                      // will pos in new bag
                for (uint32 i = 0; i< fullBag->GetBagSize(); ++i)
                {
                    Item* bagItem = fullBag->GetItemByPos(i);
                    if (!bagItem)
                        continue;

                    fullBag->RemoveItem(i, true);
                    emptyBag->StoreItem(count, bagItem, true);
                    bagItem->SetState(ITEM_CHANGED, this);

                    ++count;
                }
            }
        }
    }

    // now do moves, remove...
    RemoveItem(dstbag, dstslot, false);
    RemoveItem(srcbag, srcslot, false);

    // add to dest
    if (IsInventoryPos(dst))
        StoreItem(sDest, pSrcItem, true);
    else if (IsBankPos(dst))
        BankItem(sDest, pSrcItem, true);
    else if (IsReagentBankPos(dst))
        BankItem(sDest, pSrcItem, true);
    else if (IsEquipmentPos(dst))
        EquipItem(eDest, pSrcItem, true);

    // add to src
    if (IsInventoryPos(src))
        StoreItem(sDest2, pDstItem, true);
    else if (IsBankPos(src))
        BankItem(sDest2, pDstItem, true);
    else if (IsReagentBankPos(src))
        BankItem(sDest2, pDstItem, true);
    else if (IsEquipmentPos(src))
        EquipItem(eDest2, pDstItem, true);

    // if player is moving bags and is looting an item inside this bag
    // release the loot
    if (GetLootGUID())
    {
        bool released = false;
        if (IsBagPos(src))
        {
            Bag* bag = pSrcItem->ToBag();
            for (uint32 i = 0; i < bag->GetBagSize(); ++i)
            {
                if (Item* bagItem = bag->GetItemByPos(i))
                {
                    if (bagItem->m_lootGenerated)
                    {
                        m_session->DoLootRelease(GetLootGUID());
                        released = true;                    // so we don't need to look at dstBag
                        break;
                    }
                }
            }
        }

        if (!released && IsBagPos(dst) && pDstItem)
        {
            Bag* bag = pDstItem->ToBag();
            for (uint32 i = 0; i < bag->GetBagSize(); ++i)
            {
                if (Item* bagItem = bag->GetItemByPos(i))
                {
                    if (bagItem->m_lootGenerated)
                    {
                        m_session->DoLootRelease(GetLootGUID());
                        released = true;                    // not realy needed here ///< yeah because released is never read 01/18/16<--- Variable 'released' is assigned a value that is never used.
                        break;
                    }
                }
            }
        }
    }
    AutoUnequipOffhandIfNeed();
}

void Player::AddItemToBuyBackSlot(Item* pItem)
{
    if (pItem)
    {
        uint32 slot = m_currentBuybackSlot;
        // if current back slot non-empty search oldest or free
        if (m_items[slot])
        {
            uint32 oldest_time = GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP);
            uint32 oldest_slot = BUYBACK_SLOT_START;

            for (uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i)
            {
                // found empty
                if (!m_items[i])
                {
                    slot = i; ///< slot is never read 01/18/16
                    break;
                }

                uint32 i_time = GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP + i - BUYBACK_SLOT_START);

                if (oldest_time > i_time)
                {
                    oldest_time = i_time;
                    oldest_slot = i;
                }
            }

            // find oldest
            slot = oldest_slot;
        }

        RemoveItemFromBuyBackSlot(slot, true);
        sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);

        for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; i++)
        {
            if (m_items[i] == pItem)
            {
                ACE_Stack_Trace trace;
                sLog->outAshran("VisualizeItem duplicate item ptr ! Try to put item in slot %u already exist in slot %u ! StackTrace : %s", i, slot, trace.c_str());
            }
        }
        m_items[slot] = pItem;
        time_t base = time(NULL);
        uint32 etime = uint32(base - m_logintime + (30 * 3600));
        uint32 eslot = slot - BUYBACK_SLOT_START;

        SetGuidValue(PLAYER_FIELD_INV_SLOTS + (BUYBACK_SLOT_START * 4) + (eslot * 4), pItem->GetGUID());
        if (ItemTemplate const* proto = pItem->GetTemplate())
            SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE + eslot, proto->SellPrice * pItem->GetCount());
        else
            SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE + eslot, 0);
        SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP + eslot, (uint32)etime);

        // move to next (for non filled list is move most optimized choice)
        if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
            ++m_currentBuybackSlot;
    }
}

Item* Player::GetItemFromBuyBackSlot(uint32 slot)
{
    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
    if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
        return m_items[slot];
    return NULL;
}

void Player::RemoveItemFromBuyBackSlot(uint32 slot, bool del)
{
    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
    if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
    {
        Item* pItem = m_items[slot];
        if (pItem)
        {
            pItem->RemoveFromWorld();
            if (del)
                pItem->SetState(ITEM_REMOVED, this);
        }

        m_items[slot] = NULL;

        uint32 eslot = slot - BUYBACK_SLOT_START;
        SetGuidValue(PLAYER_FIELD_INV_SLOTS + (BUYBACK_SLOT_START * 4) + (slot * 4), 0);
        SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE + eslot, 0);
        SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP + eslot, 0);

        // if current backslot is filled set to now free slot
        if (m_items[m_currentBuybackSlot])
            m_currentBuybackSlot = slot;
    }
}

void Player::SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2, uint32 itemid)
{
    if (msg != EQUIP_ERR_OK)
    {
        WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE);

        data << uint8(msg);
        data.appendPackGUID(pItem ? pItem->GetGUID() : 0);
        data.appendPackGUID(pItem2 ? pItem2->GetGUID() : 0);
        data << uint8(0);                                   // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2

        if (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I || msg == EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW)
        {
            ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid);
            data << uint32(proto ? proto->RequiredLevel : 0);
        }

        // no idea about this one...
        if (msg == EQUIP_ERR_NO_OUTPUT)
        {
            data.appendPackGUID(0);
            data << uint32(0); // slot
            data.appendPackGUID(0);
        }

        if (msg == EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS ||
            msg == EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS ||
            msg == EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS)
        {
            ItemTemplate const* proto = pItem ? pItem->GetTemplate() : sObjectMgr->GetItemTemplate(itemid);
            data << uint32(proto ? proto->ItemLimitCategory : 0);
        }

        GetSession()->SendPacket(&data);
    }
}

void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 /*param*/)
{
    WorldPacket data(SMSG_BUY_FAILED, (8+4+4+1));
    ObjectGuid guid = creature ? creature->GetGUID() : 0;

    data.appendPackGUID(guid);
    data << uint32(item);
    data << uint8(msg);

    GetSession()->SendPacket(&data);
}

void Player::SendSellError(SellResult msg, Creature* creature, uint64 guid)
{
    ObjectGuid itemGuid = guid;
    ObjectGuid npcGuid = creature ? creature->GetGUID() : 0;
    WorldPacket data(SMSG_SELL_ITEM);

    data.appendPackGUID(npcGuid);
    data.appendPackGUID(itemGuid);
    data << uint8(msg);

    GetSession()->SendPacket(&data);
}

void Player::TradeCancel(bool sendback)
{
    if (m_trade)
    {
        Player* trader = m_trade->GetTrader();

        // send yellow "Trade canceled" message to both traders
        if (sendback)
            GetSession()->SendCancelTrade();

        trader->GetSession()->SendCancelTrade();

        // cleanup
        delete m_trade;
        m_trade = NULL;
        delete trader->m_trade;
        trader->m_trade = NULL;
    }
}

void Player::UpdateSoulboundTradeItems()
{
    if (m_itemSoulboundTradeable.empty())
        return;

    // also checks for garbage data
    for (ItemDurationList::iterator itr = m_itemSoulboundTradeable.begin(); itr != m_itemSoulboundTradeable.end();)
    {
        ASSERT(*itr);
        if ((*itr)->GetOwnerGUID() != GetGUID())
        {
            m_itemSoulboundTradeable.erase(itr++);
            continue;
        }
        if ((*itr)->CheckSoulboundTradeExpire())
        {
            m_itemSoulboundTradeable.erase(itr++);
            continue;
        }
        ++itr;
    }
}

void Player::AddTradeableItem(Item* item)
{
    m_itemSoulboundTradeable.push_back(item);
}

//TODO: should never allow an item to be added to m_itemSoulboundTradeable twice
void Player::RemoveTradeableItem(Item* item)
{
    m_itemSoulboundTradeable.remove(item);
}

void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
{
    if (m_itemDuration.empty())
        return;

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Player::UpdateItemDuration(%u, %u)", time, realtimeonly);

    for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end();)
    {
        Item* item = *itr;
        ++itr;                                              // current element can be erased in UpdateDuration

        if (!realtimeonly || item->GetTemplate()->FlagsCu & ITEM_FLAGS_CU_DURATION_REAL_TIME)
            item->UpdateDuration(this, time);
    }
}

void Player::UpdateEnchantTime(uint32 time)
{
    for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr=next)
    {
        ASSERT(itr->item);
        next = itr;
        if (!itr->item->GetEnchantmentId(itr->slot))
        {
            next = m_enchantDuration.erase(itr);
        }
        else if (itr->leftduration <= time)
        {
            ApplyEnchantment(itr->item, itr->slot, false, false);
            itr->item->ClearEnchantment(itr->slot);
            next = m_enchantDuration.erase(itr);
        }
        else if (itr->leftduration > time)<--- Condition 'itr.leftduration>time' is always true
        {
            itr->leftduration -= time;
            ++next;
        }
    }
}

void Player::AddEnchantmentDurations(Item* item)
{
    for (int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
    {
        if (x > ENGINEERING_ENCHANTMENT_SLOT && x < PROP_ENCHANTMENT_SLOT_0)    // not holding enchantment id
            continue;

        if (!item->GetEnchantmentId(EnchantmentSlot(x)))
            continue;

        uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
        if (duration > 0)
            AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
    }
}

void Player::RemoveEnchantmentDurations(Item* item)
{
    for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
    {
        if (itr->item == item)
        {
            // save duration in item
            item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration, this);
            itr = m_enchantDuration.erase(itr);
        }
        else
            ++itr;
    }
}

void Player::RemoveArenaEnchantments(EnchantmentSlot slot)
{
    // remove enchantments from equipped items first to clean up the m_enchantDuration list
    for (EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
    {
        next = itr;
        if (itr->slot == slot)
        {
            if (itr->item && itr->item->GetEnchantmentId(slot))
            {
                // Poisons and DK runes are enchants which are allowed on arenas
                if (sSpellMgr->IsArenaAllowedEnchancment(itr->item->GetEnchantmentId(slot)))
                {
                    ++next;
                    continue;
                }
                // remove from stats
                ApplyEnchantment(itr->item, slot, false, false);
                // remove visual
                itr->item->ClearEnchantment(slot);
            }
            // remove from update list
            next = m_enchantDuration.erase(itr);
        }
        else
            ++next;
    }

    // remove enchants from inventory items
    // NOTE: no need to remove these from stats, since these aren't equipped
    // in inventory
    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
        if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
            if (pItem->GetEnchantmentId(slot))
                pItem->ClearEnchantment(slot);

    // in inventory bags
    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
        if (Bag* pBag = GetBagByPos(i))
            for (uint32 j = 0; j < pBag->GetBagSize(); j++)
                if (Item* pItem = pBag->GetItemByPos(j))
                    if (pItem->GetEnchantmentId(slot))
                        pItem->ClearEnchantment(slot);
}

// duration == 0 will remove item enchant
void Player::AddEnchantmentDuration(Item* item, EnchantmentSlot slot, uint32 duration)
{
    if (!item)
        return;

    if (slot >= MAX_ENCHANTMENT_SLOT)
        return;

    for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
    {
        if (itr->item == item && itr->slot == slot)
        {
            itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration, this);
            m_enchantDuration.erase(itr);
            break;
        }
    }
    if (item && duration > 0)
    {
        GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
        m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
    }
}

void Player::ApplyEnchantment(Item* item, bool apply)
{
    for (uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
        ApplyEnchantment(item, EnchantmentSlot(slot), apply);

    //ApplyItemUpgrade(item, apply);
}

void Player::ApplyEnchantment(Item* item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
{
    if (!item || !item->IsEquipped())
        return;

    if (slot >= MAX_ENCHANTMENT_SLOT)
        return;

    uint32 enchant_id = item->GetEnchantmentId(slot);
    if (!enchant_id)
        return;

    SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
    if (!pEnchant)
        return;

    if (!ignore_condition && pEnchant->EnchantmentCondition && !EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
        return;

    if (pEnchant->requiredLevel > getLevel())
        return;

    if (pEnchant->requiredSkill > 0 && pEnchant->requiredSkillValue > GetSkillValue(pEnchant->requiredSkill))
        return;

    // Cogwheel gems dont have requirement data set in SpellItemEnchantment.dbc, but they do have it in Item-sparse.db2
    if (ItemTemplate const* gem = sObjectMgr->GetItemTemplate(pEnchant->GemID))
        if (gem->RequiredSkill && GetSkillValue(gem->RequiredSkill) < gem->RequiredSkillRank)
            return;

    // If we're dealing with a gem inside a prismatic socket we need to check the prismatic socket requirements
    // rather than the gem requirements itself. If the socket has no color it is a prismatic socket.
    // If the socket is from an item bonus, it's a WoD item, so it can't be a "classical" enchant neither a prismatic enchant
    if ((slot == SOCK_ENCHANTMENT_SLOT || slot == SOCK_ENCHANTMENT_SLOT_2 || slot == SOCK_ENCHANTMENT_SLOT_3)
        && !item->GetTemplate()->Socket[slot-SOCK_ENCHANTMENT_SLOT].Color && !item->HasItemBonusType(ItemBonusType::ITEM_BONUS_ADD_SOCKET))
    {
         // Check if the requirements for the prismatic socket are met before applying the gem stats
         SpellItemEnchantmentEntry const* pPrismaticEnchant = sSpellItemEnchantmentStore.LookupEntry(item->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT));
         if (!pPrismaticEnchant || (pPrismaticEnchant->requiredSkill > 0 && pPrismaticEnchant->requiredSkillValue > GetSkillValue(pPrismaticEnchant->requiredSkill)))
             return;
    }

    if (!item->CantBeUse())
    {
        for (int s = 0; s < MAX_ENCHANTMENT_SPELLS; ++s)
        {
            uint32 enchant_display_type = pEnchant->type[s];
            uint32 enchant_amount = CalculateEnchantmentBonus(pEnchant, pEnchant->amount[s], s, getLevel());
            uint32 enchant_spell_id = pEnchant->spellid[s];

            switch (enchant_display_type)
            {
                case ITEM_ENCHANTMENT_TYPE_NONE:
                    break;
                case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
                    // processed in Player::CastItemCombatSpell
                    break;
                case ITEM_ENCHANTMENT_TYPE_DAMAGE:
                    if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND && (
                        item->GetTemplate()->InventoryType == INVTYPE_RANGED || item->GetTemplate()->InventoryType == INVTYPE_THROWN ||
                        item->GetTemplate()->InventoryType == INVTYPE_RANGEDRIGHT))
                        HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
                    else if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
                        HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
                    else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
                        HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
                    break;
                case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
                    if (enchant_spell_id)
                    {
                        if (apply)
                        {
                            int32 basepoints = 0;
                            // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
                            if (item->GetItemRandomPropertyId() < 0)
                            {
                                ItemRandomSuffixEntry const* item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
                                if (item_rand)
                                {
                                    // Search enchant_amount
                                    for (int k = 0; k < 5; ++k)
                                    {
                                        if (item_rand->enchant_id[k] == enchant_id)
                                        {
                                            basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000);
                                            break;
                                        }
                                    }
                                }
                            }
                            // Cast custom spell vs all equal basepoints got from enchant_amount
                            if (basepoints)
                                CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
                            else
                                CastSpell(this, enchant_spell_id, true, item);
                        }
                        else
                            RemoveAurasDueToItemSpell(item, enchant_spell_id);
                    }
                    break;
                case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
                    if (!enchant_amount)
                    {
                        ItemRandomSuffixEntry const* item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
                        if (item_rand)
                        {
                            for (int k = 0; k < MAX_ITEM_ENCHANTMENT_EFFECTS; ++k)
                            {
                                if (item_rand->enchant_id[k] == enchant_id)
                                {
                                    enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000);
                                    break;
                                }
                            }
                        }
                    }

                    HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
                    break;
                case ITEM_ENCHANTMENT_TYPE_STAT:
                {
                    if (!enchant_amount)
                    {
                        ItemRandomSuffixEntry const* item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
                        if (item_rand_suffix)
                        {
                            for (int k = 0; k < 5; ++k)
                            {
                                if (item_rand_suffix->enchant_id[k] == enchant_id)
                                {
                                    enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000);
                                    break;
                                }
                            }
                        }
                    }

                    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Adding %u to stat nb %u", enchant_amount, enchant_spell_id);
                    switch (enchant_spell_id)
                    {
                        case ITEM_MOD_MANA:
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA", enchant_amount);
                            HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
                            break;
                        case ITEM_MOD_HEALTH:
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH", enchant_amount);
                            HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
                            break;
                        case ITEM_MOD_AGILITY:
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u AGILITY", enchant_amount);
                            HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
                            ApplyStatBuffMod(STAT_AGILITY, (float)enchant_amount, apply);
                            break;
                        case ITEM_MOD_STRENGTH:
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u STRENGTH", enchant_amount);
                            HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
                            ApplyStatBuffMod(STAT_STRENGTH, (float)enchant_amount, apply);
                            break;
                        case ITEM_MOD_INTELLECT:
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u INTELLECT", enchant_amount);
                            HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
                            ApplyStatBuffMod(STAT_INTELLECT, (float)enchant_amount, apply);
                            break;
                        case ITEM_MOD_SPIRIT:
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPIRIT", enchant_amount);
                            HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
                            ApplyStatBuffMod(STAT_SPIRIT, (float)enchant_amount, apply);
                            break;
                        case ITEM_MOD_STAMINA:
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u STAMINA", enchant_amount);
                            HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
                            ApplyStatBuffMod(STAT_STAMINA, (float)enchant_amount, apply);
                            break;
                        case ITEM_MOD_DODGE_RATING:
                            ApplyRatingMod(CR_DODGE, enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u DODGE", enchant_amount);
                            break;
                        case ITEM_MOD_PARRY_RATING:
                            ApplyRatingMod(CR_PARRY, enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u PARRY", enchant_amount);
                            break;
                        case ITEM_MOD_BLOCK_RATING:
                            ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SHIELD_BLOCK", enchant_amount);
                            break;
                        case ITEM_MOD_CRIT_RATING:
                            ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
                            ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
                            ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u CRITICAL", enchant_amount);
                            break;
                        case ITEM_MOD_RESILIENCE_RATING:
                            ApplyRatingMod(CR_RESILIENCE_PLAYER_DAMAGE_TAKEN, enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u RESILIENCE", enchant_amount);
                            break;
                        case ITEM_MOD_HASTE_RATING:
                            ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
                            ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
                            ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HASTE", enchant_amount);
                            break;
                        case ITEM_MOD_ATTACK_POWER:
                            HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
                            HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u ATTACK_POWER", enchant_amount);
                            break;
                        case ITEM_MOD_VERSATILITY_RATING:
                            ApplyRatingMod(CR_VERSATILITY_DAMAGE_DONE, enchant_amount, apply);
                            ApplyRatingMod(CR_VERSATILITY_DAMAGE_TAKEN, enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u VERSATILITY", enchant_amount);
                            break;
                        case ITEM_MOD_MANA_REGENERATION:
                            ApplyManaRegenBonus(enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MANA_REGENERATION", enchant_amount);
                            break;
                        case ITEM_MOD_SPELL_POWER:
                            ApplySpellPowerBonus(enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SPELL_POWER", enchant_amount);
                            break;
                        case ITEM_MOD_HEALTH_REGEN:
                            ApplyHealthRegenBonus(enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HEALTH_REGENERATION", enchant_amount);
                            break;
                        case ITEM_MOD_MASTERY_RATING:
                            ApplyRatingMod(CR_MASTERY, int32(enchant_amount), apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MASTERY_RATING", enchant_amount);
                            break;
                        case ITEM_MOD_FIRE_RESISTANCE:
                            HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(enchant_amount), apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u FIRE RESISTANCE", enchant_amount);
                            break;
                        case ITEM_MOD_FROST_RESISTANCE:
                            HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(enchant_amount), apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u FROST RESISTANCE", enchant_amount);
                            break;
                        case ITEM_MOD_HOLY_RESISTANCE:
                            HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(enchant_amount), apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u HOLY RESISTANCE", enchant_amount);
                            break;
                        case ITEM_MOD_SHADOW_RESISTANCE:
                            HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(enchant_amount), apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u SHADOW RESISTANCE", enchant_amount);
                            break;
                        case ITEM_MOD_NATURE_RESISTANCE:
                            HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(enchant_amount), apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u NATURE RESISTANCE", enchant_amount);
                            break;
                        case ITEM_MOD_ARCANE_RESISTANCE:
                            HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(enchant_amount), apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u ARCANE RESISTANCE", enchant_amount);
                            break;
                        case ITEM_MOD_PVP_POWER:
                            ApplyRatingMod(CR_PVP_POWER, enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u POWER JCJ", enchant_amount);
                            break;
                        case ITEM_MOD_MULTISTRIKE_RATING:
                            ApplyRatingMod(CR_MULTISTRIKE, enchant_amount, apply);
                            sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "+ %u MULTISTRIKE", enchant_amount);
                            break;
                        case ITEM_MOD_DYNAMIC_STAT_AGI_STR_INT:
                        {
                            Stats stat = GetPrimaryStat();
                            HandleStatModifier((UnitMods)stat, BASE_VALUE, float(enchant_amount), apply);
                            ApplyStatBuffMod(stat, float(enchant_amount), apply);
                            break;
                        }
                        case ITEM_MOD_DYNAMIC_STAT_AGI_STR:
                        {
                            Stats stat = GetPrimaryStat();
                            if (stat != STAT_AGILITY && stat != STAT_STRENGTH)
                                break;

                            HandleStatModifier((UnitMods)stat, BASE_VALUE, float(enchant_amount), apply);
                            ApplyStatBuffMod(stat, float(enchant_amount), apply);
                            break;
                        }
                        case ITEM_MOD_DYNAMIC_STAT_AGI_INT:
                        {
                            Stats stat = GetPrimaryStat();
                            if (stat != STAT_AGILITY && stat != STAT_INTELLECT)
                                break;

                            HandleStatModifier((UnitMods)stat, BASE_VALUE, float(enchant_amount), apply);
                            ApplyStatBuffMod(stat, float(enchant_amount), apply);
                            break;
                        }
                        case ITEM_MOD_DYNAMIC_STAT_STR_INT:
                        {
                            Stats stat = GetPrimaryStat();
                            if (stat != STAT_INTELLECT && stat != STAT_STRENGTH)
                                break;

                            HandleStatModifier((UnitMods)stat, BASE_VALUE, float(enchant_amount), apply);
                            ApplyStatBuffMod(stat, float(enchant_amount), apply);
                            break;
                        }
                        default:
                            break;
                    }
                    break;
                }
                case ITEM_ENCHANTMENT_TYPE_TOTEM:           // Shaman Rockbiter Weapon
                {
                    if (getClass() == CLASS_SHAMAN)
                    {
                        float addValue = 0.0f;
                        if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
                        {
                            addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f);
                            HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
                        }
                        else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
                        {
                            addValue = float(enchant_amount * item->GetTemplate()->Delay / 1000.0f);
                            HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
                        }
                    }
                    break;
                }
                case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
                    // processed in Player::CastItemUseSpell
                    break;
                case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
                    // nothing do..
                    break;
                default:
                    sLog->outError(LOG_FILTER_PLAYER, "Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
                    break;
            }                                               /*switch (enchant_display_type)*/
        }                                                   /*for*/
    }

    // visualize enchantment at player and equipped items
    if (slot == PERM_ENCHANTMENT_SLOT)
        SetUInt16Value(PLAYER_FIELD_VISIBLE_ITEMS + (item->GetSlot() * 2) + 1, 1, apply ? item->GetEnchantItemVisualId(slot) : 0);

    if (slot == TEMP_ENCHANTMENT_SLOT)
        SetUInt16Value(PLAYER_FIELD_VISIBLE_ITEMS + (item->GetSlot() * 2) + 1, 1, apply ? item->GetEnchantItemVisualId(slot) : 0);

    if (apply_dur)
    {
        if (apply)
        {
            // set duration
            uint32 duration = item->GetEnchantmentDuration(slot);
            if (duration > 0)
                AddEnchantmentDuration(item, slot, duration);
        }
        else
        {
            // duration == 0 will remove EnchantDuration
            AddEnchantmentDuration(item, slot, 0);
        }
    }
}

void Player::UpdateSkillEnchantments(uint16 skill_id, uint16 curr_value, uint16 new_value)
{
    for (uint8 i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        if (m_items[i])
        {
            for (uint8 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
            {
                if (slot > ENGINEERING_ENCHANTMENT_SLOT && slot < PROP_ENCHANTMENT_SLOT_0)    // not holding enchantment id
                    continue;

                uint32 ench_id = m_items[i]->GetEnchantmentId(EnchantmentSlot(slot));
                if (!ench_id)
                    continue;

                SpellItemEnchantmentEntry const* Enchant = sSpellItemEnchantmentStore.LookupEntry(ench_id);
                if (!Enchant)
                    return;

                if (Enchant->requiredSkill == skill_id)
                {
                    // Checks if the enchantment needs to be applied or removed
                    if (curr_value < Enchant->requiredSkillValue && new_value >= Enchant->requiredSkillValue)
                        ApplyEnchantment(m_items[i], EnchantmentSlot(slot), true);
                    else if (new_value < Enchant->requiredSkillValue && curr_value >= Enchant->requiredSkillValue)
                        ApplyEnchantment(m_items[i], EnchantmentSlot(slot), false);
                }

                // If we're dealing with a gem inside a prismatic socket we need to check the prismatic socket requirements
                // rather than the gem requirements itself. If the socket has no color it is a prismatic socket.
                if ((slot == SOCK_ENCHANTMENT_SLOT || slot == SOCK_ENCHANTMENT_SLOT_2 || slot == SOCK_ENCHANTMENT_SLOT_3)
                    && !m_items[i]->GetTemplate()->Socket[slot-SOCK_ENCHANTMENT_SLOT].Color)
                {
                    SpellItemEnchantmentEntry const* pPrismaticEnchant = sSpellItemEnchantmentStore.LookupEntry(m_items[i]->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT));

                    if (pPrismaticEnchant && pPrismaticEnchant->requiredSkill == skill_id)
                    {
                        if (curr_value < pPrismaticEnchant->requiredSkillValue && new_value >= pPrismaticEnchant->requiredSkillValue)
                            ApplyEnchantment(m_items[i], EnchantmentSlot(slot), true);
                        else if (new_value < pPrismaticEnchant->requiredSkillValue && curr_value >= pPrismaticEnchant->requiredSkillValue)
                            ApplyEnchantment(m_items[i], EnchantmentSlot(slot), false);
                    }
                }
            }
        }
    }
}

void Player::SendEnchantmentDurations()
{
    for (EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
        GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
}

void Player::SendItemDurations()
{
    for (ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
        (*itr)->SendTimeUpdate(this);
}

void Player::SendDisplayToast(uint32 p_Entry, uint32 p_Count, DisplayToastMethod p_Method, ToastTypes p_Type, bool p_BonusRoll, bool p_Mailed, std::vector<uint32> const& p_ItemBonus)
{
    ItemTemplate const* l_ItemTpl = sObjectMgr->GetItemTemplate(p_Entry);

    if (!l_ItemTpl && p_Entry && p_Type == TOAST_TYPE_NEW_ITEM)
        return;

    WorldPacket l_Data(SMSG_DISPLAY_TOAST, 30);

    l_Data << uint32(p_Count);
    l_Data << uint8(p_Method);                  ///< DisplayToastMethod

    l_Data.WriteBit(p_BonusRoll);               ///< Bonuses
    l_Data.WriteBits(p_Type, 2);                ///< Context

    if (p_Type == TOAST_TYPE_NEW_ITEM)
    {
        l_Data.WriteBit(p_Mailed);
        l_Data.FlushBits();

        Item::BuildDynamicItemDatas(l_Data, p_Entry, p_ItemBonus);

        l_Data << uint32(GetLootSpecId());          ///< LootSpec
        l_Data << uint32(0);                        ///< Quantity
    }
    else
        l_Data.FlushBits();

    if (p_Type == TOAST_TYPE_NEW_CURRENCY)
        l_Data << uint32(p_Entry);

    GetSession()->SendPacket(&l_Data);
}

void Player::SendNewItem(Item* p_Item, uint32 p_Quantity, bool p_Received, bool p_Created, bool p_Broadcast, uint32 p_EncounterID /*= 0*/, ItemContext p_Context /*= ItemContext::None*/)
{
    /// Prevent crash
    if (!p_Item)
        return;

    WorldPacket l_Data(Opcodes::SMSG_ITEM_PUSH_RESULT, 16 + 2 + 1 + 4 + 100 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 16 + 2 + 1);

    l_Data.appendPackGUID(GetGUID());                               ///< Player GUID
    l_Data << uint8(p_Item->GetBagSlot());                          ///< Slot
    l_Data << uint32(0);                                            ///< SlotInBag

    Item::BuildDynamicItemDatas(l_Data, p_Item, p_Context);

    l_Data << uint32(0);                                            ///< QuestLogItemID
    l_Data << uint32(p_Quantity);                                   ///< Quantity
    l_Data << uint32(GetItemCount(p_Item->GetEntry()));             ///< count of items in inventory
    l_Data << uint32(p_EncounterID);                                ///< Dungeon Encounter ID
    l_Data << uint32(0);                                            ///< Battle Pet Species ID
    l_Data << uint32(0);                                            ///< Battle Pet Breed ID
    l_Data << uint32(0);                                            ///< Battle Pet Breed Quality
    l_Data << uint32(0);                                            ///< Battle Pet Level
    l_Data.appendPackGUID(p_Item->GetGUID());                       ///< Item GUID

    l_Data.WriteBit(p_Received);                                    ///< Pushed
    l_Data.WriteBit(p_Created);                                     ///< Created
    l_Data.WriteBits(p_Context == ItemContext::RaidLfr ? 3 : 1, 2); ///< Display Text
    l_Data.WriteBit(false);                                         ///< Is Bonus Roll
    l_Data.WriteBit(p_Context == ItemContext::RaidLfr);             ///< Is Encounter Loot
    l_Data.FlushBits();

    if (p_Broadcast && GetGroup())
        GetGroup()->BroadcastPacket(&l_Data, true);
    else
        GetSession()->SendPacket(&l_Data);
}

/*********************************************************/
/***                    GOSSIP SYSTEM                  ***/
/*********************************************************/
void Player::PrepareGossipMenu(WorldObject* source, uint32 menuId /*= 0*/, bool showQuests /*= false*/)
{
    PlayerMenu* menu = PlayerTalkClass;
    menu->ClearMenus();

    menu->GetGossipMenu().SetMenuId(menuId);

    GossipMenuItemsMapBounds menuItemBounds = sObjectMgr->GetGossipMenuItemsMapBounds(menuId);

    // if default menuId and no menu options exist for this, use options from default options
    if (menuItemBounds.first == menuItemBounds.second && menuId == GetDefaultGossipMenuForSource(source))
        menuItemBounds = sObjectMgr->GetGossipMenuItemsMapBounds(0);

    uint32 npcflags = 0;

    if (source->GetTypeId() == TYPEID_UNIT)
    {
        npcflags = source->GetUInt32Value(UNIT_FIELD_NPC_FLAGS);
        if (showQuests && npcflags & UNIT_NPC_FLAG_QUESTGIVER)
            PrepareQuestMenu(source->GetGUID());
    }

    else if (source->GetTypeId() == TYPEID_GAMEOBJECT)
        if (showQuests && source->ToGameObject()->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
            PrepareQuestMenu(source->GetGUID());

    for (GossipMenuItemsContainer::const_iterator itr = menuItemBounds.first; itr != menuItemBounds.second; ++itr)
    {
        bool canTalk = true;
        if (!sConditionMgr->IsObjectMeetToConditions(this, source, itr->second.Conditions))
            continue;

        if (Creature* creature = source->ToCreature())
        {
            if (!(itr->second.OptionNpcflag & npcflags))
                continue;

            switch (itr->second.OptionType)
            {
                case GOSSIP_OPTION_ARMORER:
                    canTalk = false;                       // added in special mode
                    break;
                case GOSSIP_OPTION_SPIRITHEALER:
                    if (!isDead())
                        canTalk = false;
                    break;
                case GOSSIP_OPTION_VENDOR:
                {
                    VendorItemData const* vendorItems = creature->GetVendorItems();
                    if (!vendorItems || vendorItems->Empty())
                    {
                        sLog->outError(LOG_FILTER_SQL, "Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", creature->GetGUIDLow(), creature->GetEntry());
                        canTalk = false;
                    }
                    break;
                }
                case GOSSIP_OPTION_TRAINER:
                    if (!creature->isCanTrainingOf(this, false))
                        canTalk = false;
                    break;
                case GOSSIP_OPTION_LEARNDUALSPEC:
                    if (!(GetSpecsCount() == 1 && creature->isCanTrainingAndResetTalentsOf(this) && !(getLevel() < sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL))))
                        canTalk = false;
                    break;
                case GOSSIP_OPTION_UNLEARNTALENTS:
                    if (!creature->isCanTrainingAndResetTalentsOf(this))
                        canTalk = false;
                    break;
                case GOSSIP_OPTION_UNLEARNPETTALENTS:
                    if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || creature->GetCreatureTemplate()->trainer_type != TRAINER_TYPE_PETS || creature->GetCreatureTemplate()->trainer_class != CLASS_HUNTER)
                        canTalk = false;
                    break;
                case GOSSIP_OPTION_UNLEARNSPECIALIZATION:
                    if (!creature->isCanTrainingAndResetTalentsOf(this))
                        canTalk = false;
                    break;
                case GOSSIP_OPTION_TAXIVENDOR:
                    if (GetSession()->SendLearnNewTaxiNode(creature))
                        return;
                    break;
                case GOSSIP_OPTION_BATTLEFIELD:
                    if (!creature->isCanInteractWithBattleMaster(this, false))
                        canTalk = false;
                    break;
                case GOSSIP_OPTION_STABLEPET:
                    if (getClass() != CLASS_HUNTER)
                        canTalk = false;
                    break;
                case GOSSIP_OPTION_QUESTGIVER:
                    canTalk = false;
                    break;
                case GOSSIP_OPTION_GOSSIP:
                case GOSSIP_OPTION_SPIRITGUIDE:
                case GOSSIP_OPTION_INNKEEPER:
                case GOSSIP_OPTION_BANKER:
                case GOSSIP_OPTION_PETITIONER:
                case GOSSIP_OPTION_TABARDDESIGNER:
                case GOSSIP_OPTION_AUCTIONEER:
                    break;                                  // no checks
                case GOSSIP_OPTION_OUTDOORPVP:
                    if (!sOutdoorPvPMgr->CanTalkTo(this, creature, itr->second))
                        canTalk = false;
                    break;
                default:
                    sLog->outError(LOG_FILTER_SQL, "Creature entry %u have unknown gossip option %u for menu %u", creature->GetEntry(), itr->second.OptionType, itr->second.MenuId);
                    canTalk = false;
                    break;
            }
        }
        else if (GameObject* go = source->ToGameObject())
        {
            switch (itr->second.OptionType)
            {
                case GOSSIP_OPTION_GOSSIP:
                    if (go->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && go->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
                        canTalk = false;
                    break;
                default:
                    canTalk = false;
                    break;
            }
        }

        if (canTalk)
        {
            std::string strOptionText = itr->second.OptionText;
            std::string strBoxText = itr->second.BoxText;

            int32 locale = GetSession()->GetSessionDbLocaleIndex();
            if (locale >= 0)
            {
                if (GossipMenuItemsLocale const* no = sObjectMgr->GetGossipMenuItemsLocale(MAKE_PAIR64(menuId, itr->second.OptionIndex)))
                {
                    ObjectMgr::GetLocaleString(no->OptionText, locale, strOptionText);
                    ObjectMgr::GetLocaleString(no->BoxText, locale, strBoxText);
                }
            }

            menu->GetGossipMenu().AddMenuItem(itr->second.OptionIndex, itr->second.OptionIcon, strOptionText, 0, itr->second.OptionType, strBoxText, itr->second.BoxMoney, itr->second.BoxCoded);
            menu->GetGossipMenu().AddGossipMenuItemData(itr->second.OptionIndex, itr->second.ActionMenuId, itr->second.ActionPoiId);
        }
    }
}

void Player::SendPreparedGossip(WorldObject* source)
{
    if (!source)
        return;

    if (source->GetTypeId() == TYPEID_UNIT)
    {
        // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
        if (!source->ToCreature()->HasFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
        {
            SendPreparedQuest(source->GetGUID());
            return;
        }
    }
    else if (source->GetTypeId() == TYPEID_GAMEOBJECT)
    {
        // probably need to find a better way here
        if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
        {
            SendPreparedQuest(source->GetGUID());
            return;
        }
    }

    // in case non empty gossip menu (that not included quests list size) show it
    // (quest entries from quest menu will be included in list)

    uint32 textId = GetGossipTextId(source);

    if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
        textId = GetGossipTextId(menuId, source);

    PlayerTalkClass->SendGossipMenu(textId, source->GetGUID());
}

void Player::OnGossipSelect(WorldObject* source, uint32 gossipListId, uint32 menuId)
{
    GossipMenu& gossipMenu = PlayerTalkClass->GetGossipMenu();

    // if not same, then something funky is going on
    if (menuId != gossipMenu.GetMenuId())
        return;

    GossipMenuItem const* item = gossipMenu.GetItem(gossipListId);
    if (!item)
        return;

    uint32 gossipOptionId = item->OptionType;
    uint64 guid = source->GetGUID();

    if (source->GetTypeId() == TYPEID_GAMEOBJECT)
    {
        if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), source->GetEntry());
            return;
        }
    }

    GossipMenuItemData const* menuItemData = gossipMenu.GetItemData(gossipListId);
    if (!menuItemData)
        return;

    int32 cost = int32(item->BoxMoney);
    if (!HasEnoughMoney(int64(cost)))
    {
        SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
        PlayerTalkClass->SendCloseGossip();
        return;
    }

    switch (gossipOptionId)
    {
        case GOSSIP_OPTION_GOSSIP:
        {
            if (menuItemData->GossipActionPoi)
                PlayerTalkClass->SendPointOfInterest(menuItemData->GossipActionPoi);

            if (menuItemData->GossipActionMenuId)
            {
                PrepareGossipMenu(source, menuItemData->GossipActionMenuId);
                SendPreparedGossip(source);
            }

            break;
        }
        case GOSSIP_OPTION_OUTDOORPVP:
            sOutdoorPvPMgr->HandleGossipOption(this, source->GetGUID(), gossipListId);
            break;
        case GOSSIP_OPTION_SPIRITHEALER:
            if (isDead())
                source->ToCreature()->CastSpell(source->ToCreature(), 17251, true, NULL, nullptr, GetGUID());
            break;
        case GOSSIP_OPTION_QUESTGIVER:
            PrepareQuestMenu(guid);
            SendPreparedQuest(guid);
            break;
        case GOSSIP_OPTION_VENDOR:
        case GOSSIP_OPTION_ARMORER:
            GetSession()->SendListInventory(guid);
            break;
        case GOSSIP_OPTION_STABLEPET:
            GetSession()->SendStablePet(guid);
            break;
        case GOSSIP_OPTION_TRAINER:
            GetSession()->SendTrainerList(guid);
            break;
        case GOSSIP_OPTION_LEARNDUALSPEC:
            if (GetSpecsCount() == 1 && getLevel() >= sWorld->getIntConfig(CONFIG_MIN_DUALSPEC_LEVEL))
            {
                // Cast spells that teach dual spec
                // Both are also ImplicitTarget self and must be cast by player
                CastSpell(this, 63680, true, NULL, nullptr, GetGUID());
                CastSpell(this, 63624, true, NULL, nullptr, GetGUID());

                // Should show another Gossip text with "Congratulations..."
                PlayerTalkClass->SendCloseGossip();
            }
            break;
        case GOSSIP_OPTION_UNLEARNTALENTS:
            PlayerTalkClass->SendCloseGossip();
            SendTalentWipeConfirm(guid, false);
            break;
        case GOSSIP_OPTION_UNLEARNPETTALENTS:
            PlayerTalkClass->SendCloseGossip();
            //ResetPetTalents();
            break;
         case GOSSIP_OPTION_UNLEARNSPECIALIZATION:
            PlayerTalkClass->SendCloseGossip();
            SendTalentWipeConfirm(guid, true);
            break;
        case GOSSIP_OPTION_TAXIVENDOR:
            GetSession()->SendTaxiMenu(source->ToCreature());
            break;
        case GOSSIP_OPTION_INNKEEPER:
            PlayerTalkClass->SendCloseGossip();
            SetBindPoint(guid);
            break;
        case GOSSIP_OPTION_BANKER:
            GetSession()->SendShowBank(guid);
            break;
        case GOSSIP_OPTION_PETITIONER:
            PlayerTalkClass->SendCloseGossip();
            GetSession()->SendPetitionShowList(guid);
            break;
        case GOSSIP_OPTION_TABARDDESIGNER:
            PlayerTalkClass->SendCloseGossip();
            GetSession()->SendTabardVendorActivate(GetSession()->GetPlayer()->GetGUID());
            break;
        case GOSSIP_OPTION_AUCTIONEER:
            GetSession()->SendAuctionHello(guid, source->ToCreature());
            break;
        case GOSSIP_OPTION_SPIRITGUIDE:
            PrepareGossipMenu(source);
            SendPreparedGossip(source);
            break;
        case GOSSIP_OPTION_BATTLEFIELD:
        {
            BattlegroundTypeId bgTypeId = sBattlegroundMgr->GetBattleMasterBG(source->GetEntry());

            if (bgTypeId == BATTLEGROUND_TYPE_NONE)
            {
                sLog->outError(LOG_FILTER_PLAYER, "a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
                return;
            }

            GetSession()->SendBattleGroundList(guid, bgTypeId);
            break;
        }
    }

    ModifyMoney(-cost);
}

uint32 Player::GetGossipTextId(WorldObject* source)
{
    if (!source)
        return DEFAULT_GOSSIP_MESSAGE;

    return GetGossipTextId(GetDefaultGossipMenuForSource(source), source);
}

uint32 Player::GetGossipTextId(uint32 menuId, WorldObject* source)
{
    uint32 textId = DEFAULT_GOSSIP_MESSAGE;

    if (!menuId)
        return textId;

    GossipMenusMapBounds menuBounds = sObjectMgr->GetGossipMenusMapBounds(menuId);

    for (GossipMenusContainer::const_iterator itr = menuBounds.first; itr != menuBounds.second; ++itr)
    {
        if (sConditionMgr->IsObjectMeetToConditions(this, source, itr->second.conditions))
            textId = itr->second.text_id;
    }

    return textId;
}

uint32 Player::GetDefaultGossipMenuForSource(WorldObject* source)
{
    switch (source->GetTypeId())
    {
        case TYPEID_UNIT:
            return source->ToCreature()->GetCreatureTemplate()->GossipMenuId;
        case TYPEID_GAMEOBJECT:
            return source->ToGameObject()->GetGOInfo()->GetGossipMenuId();
        default:
            break;
    }

    return 0;
}

/*********************************************************/
/***                    QUEST SYSTEM                   ***/
/*********************************************************/
void Player::PrepareQuestMenu(uint64 guid)
{
    QuestRelationBounds objectQR;
    QuestRelationBounds objectQIR;

    // pets also can have quests
    Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
    if (creature)
    {
        objectQR  = sObjectMgr->GetCreatureQuestRelationBounds(creature->GetEntry());
        objectQIR = sObjectMgr->GetCreatureQuestInvolvedRelationBounds(creature->GetEntry());
    }
    else
    {
        //we should obtain map pointer from GetMap() in 99% of cases. Special case
        //only for quests which cast teleport spells on player
        Map* _map = IsInWorld() ? GetMap() : sMapMgr->FindMap(GetMapId(), GetInstanceId());
        ASSERT(_map);
        GameObject* pGameObject = _map->GetGameObject(guid);
        if (pGameObject)
        {
            objectQR  = sObjectMgr->GetGOQuestRelationBounds(pGameObject->GetEntry());
            objectQIR = sObjectMgr->GetGOQuestInvolvedRelationBounds(pGameObject->GetEntry());
        }
        else
            return;
    }

    QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
    qm.ClearMenu();

    std::set<uint32> l_AddedQuests;

    for (QuestRelations::const_iterator i = objectQIR.first; i != objectQIR.second; ++i)
    {
        uint32 quest_id = i->second;
        QuestStatus status = GetQuestStatus(quest_id);

        if (l_AddedQuests.find(quest_id) != l_AddedQuests.end())
            continue;

        if (status == QUEST_STATUS_COMPLETE)
        {
            l_AddedQuests.insert(quest_id);
            qm.AddMenuItem(quest_id, 4);
        }
        else if (status == QUEST_STATUS_INCOMPLETE)
        {
            l_AddedQuests.insert(quest_id);
            qm.AddMenuItem(quest_id, 4);
        }
        //else if (status == QUEST_STATUS_AVAILABLE)
        //    qm.AddMenuItem(quest_id, 2);
    }

    for (QuestRelations::const_iterator i = objectQR.first; i != objectQR.second; ++i)
    {
        uint32 quest_id = i->second;
        Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
        if (!quest)
            continue;

        if (l_AddedQuests.find(quest_id) != l_AddedQuests.end())
            continue;

        if (!CanTakeQuest(quest, false))
            continue;

        if (GetQuestStatus(quest_id) == QUEST_STATUS_NONE)
        {
            l_AddedQuests.insert(quest_id);
            qm.AddMenuItem(quest_id, 2);
        }
    }
}

void Player::SendPreparedQuest(uint64 guid)
{
    QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
    if (questMenu.Empty())
        return;

    // single element case
    if (questMenu.GetMenuItemCount() == 1)
    {
        QuestMenuItem const& qmi0 = questMenu.GetItem(0);
        uint32 questId = qmi0.QuestId;

        // Auto open -- maybe also should verify there is no greeting
        if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId))
        {
            if (qmi0.QuestIcon == 4)
                PlayerTalkClass->SendQuestGiverRequestItems(quest, guid, CanRewardQuest(quest, false), true);
            // Send completable on repeatable and autoCompletable quest if player don't have quest
            // @todo: verify if check for !quest->IsDaily() is really correct (possibly not)
            else
            {
                Object* object = ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_UNIT | TYPEMASK_GAMEOBJECT | TYPEMASK_ITEM);
                if (!object || (!object->hasQuest(questId) && !object->hasInvolvedQuest(questId)))
                {
                    PlayerTalkClass->SendCloseGossip();
                    return;
                }

                if (quest->IsAutoAccept() && CanAddQuest(quest, true) && CanTakeQuest(quest, true))
                {
                    AddQuest(quest, object);
                    if (CanCompleteQuest(questId))
                        CompleteQuest(questId);
                }

                if ((quest->IsAutoComplete() && quest->IsRepeatable() && !quest->IsDailyOrWeekly()) || quest->HasFlag(QUEST_FLAGS_AUTOCOMPLETE))
                    PlayerTalkClass->SendQuestGiverRequestItems(quest, guid, CanCompleteRepeatableQuest(quest), true);
                else
                    PlayerTalkClass->SendQuestGiverQuestDetails(quest, guid);
            }
        }
    }
    // multiple entries
    else
    {
        QEmote qe;
        qe._Delay = 0;
        qe._Emote = 0;
        std::string title = "";

        // need pet case for some quests
        Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
        if (creature)
        {
            uint32 textid = GetGossipTextId(creature);
            GossipText const* gossiptext = sObjectMgr->GetGossipText(textid);
            if (!gossiptext)
            {
                qe._Delay = 0;                              //TEXTEMOTE_MESSAGE;              //zyg: player emote
                qe._Emote = 0;                              //TEXTEMOTE_HELLO;                //zyg: NPC emote
                title = "";
            }
            else
            {
                qe = gossiptext->Options[0].Emotes[0];

                if (!gossiptext->Options[0].Text_0.empty())
                {
                    title = gossiptext->Options[0].Text_0;

                    int loc_idx = GetSession()->GetSessionDbLocaleIndex();
                    if (loc_idx >= 0)
                        if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid))
                            ObjectMgr::GetLocaleString(nl->Text_0[0], loc_idx, title);
                }
                else
                {
                    title = gossiptext->Options[0].Text_1;

                    int loc_idx = GetSession()->GetSessionDbLocaleIndex();
                    if (loc_idx >= 0)
                        if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid))
                            ObjectMgr::GetLocaleString(nl->Text_1[0], loc_idx, title);
                }
            }
        }
        PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
    }
}

bool Player::IsActiveQuest(uint32 quest_id) const
{
    return m_QuestStatus.find(quest_id) != m_QuestStatus.end();
}

Quest const* Player::GetNextQuest(uint64 guid, Quest const* quest)
{
    QuestRelationBounds objectQR;

    Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid);
    if (creature)
        objectQR  = sObjectMgr->GetCreatureQuestRelationBounds(creature->GetEntry());
    else
    {
        //we should obtain map pointer from GetMap() in 99% of cases. Special case
        //only for quests which cast teleport spells on player
        Map* _map = IsInWorld() ? GetMap() : sMapMgr->FindMap(GetMapId(), GetInstanceId());
        ASSERT(_map);
        GameObject* pGameObject = _map->GetGameObject(guid);
        if (pGameObject)
            objectQR  = sObjectMgr->GetGOQuestRelationBounds(pGameObject->GetEntry());
        else
            return NULL;
    }

    uint32 nextQuestID = quest->GetNextQuestInChain();
    for (QuestRelations::const_iterator itr = objectQR.first; itr != objectQR.second; ++itr)
    {
        if (itr->second == nextQuestID)
            return sObjectMgr->GetQuestTemplate(nextQuestID);
    }

    return NULL;
}

bool Player::CanSeeStartQuest(Quest const* quest)
{
    if (!DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this) && SatisfyQuestClass(quest, false) && SatisfyQuestRace(quest, false) &&
        SatisfyQuestSkill(quest, false) && SatisfyQuestExclusiveGroup(quest, false) && SatisfyQuestReputation(quest, false) &&
        SatisfyQuestPreviousQuest(quest, false) && SatisfyQuestNextChain(quest, false) &&
        SatisfyQuestPrevChain(quest, false) && SatisfyQuestDay(quest) && SatisfyQuestWeek(quest, false) &&
        SatisfyQuestMonth(quest, false) && SatisfyQuestSeasonal(quest, false))
    {
        return getLevel() + sWorld->getIntConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= quest->GetMinLevel();
    }

    return false;
}

bool Player::CanTakeQuest(Quest const* quest, bool msg)
{
    ///
    return !DisableMgr::IsDisabledFor(DISABLE_TYPE_QUEST, quest->GetQuestId(), this)
        && SatisfyQuestStatus(quest, msg) && SatisfyQuestExclusiveGroup(quest, msg)
        && SatisfyQuestTeam(quest)
        && SatisfyQuestClass(quest, msg) && SatisfyQuestRace(quest, msg) && SatisfyQuestLevel(quest, msg)
        && SatisfyQuestSkill(quest, msg) && SatisfyQuestReputation(quest, msg)
        && SatisfyQuestPreviousQuest(quest, msg) && SatisfyQuestTimed(quest, msg)
        && SatisfyQuestNextChain(quest, msg) && SatisfyQuestPrevChain(quest, msg)
        && SatisfyQuestDay(quest) && SatisfyQuestWeek(quest, msg)
        && SatisfyQuestMonth(quest, msg) && SatisfyQuestSeasonal(quest, msg)
        && SatisfyQuestConditions(quest, msg);
}

bool Player::CanAddQuest(Quest const* quest, bool msg)
{
    if (!SatisfyQuestLog(msg))
        return false;

    uint32 srcitem = quest->GetSrcItemId();
    if (srcitem > 0)
    {
        ItemPosCountVec dest;
        InventoryResult msg2 = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, srcitem, QUEST_SOURCE_ITEM_COUNT);

        // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
        if (msg2 == EQUIP_ERR_ITEM_MAX_COUNT)
            return true;
        else if (msg2 != EQUIP_ERR_OK)
        {
            SendEquipError(msg2, NULL, NULL, srcitem);
            return false;
        }
    }
    return true;
}

bool Player::CanCompleteQuest(uint32 p_QuestID)
{
    if (p_QuestID)
    {
        Quest const* l_Quest = sObjectMgr->GetQuestTemplate(p_QuestID);

        if (!l_Quest)
            return false;

        if (!l_Quest->IsRepeatable() && m_RewardedQuests.find(p_QuestID) != m_RewardedQuests.end())
            return false;                                   // not allow re-complete quest

        // auto complete quest
        if (l_Quest->IsAutoComplete() && CanTakeQuest(l_Quest, false))
        {
            return true;
        }

        QuestStatusMap::iterator itr = m_QuestStatus.find(p_QuestID);
        if (itr == m_QuestStatus.end())
            return false;

        QuestStatusData &q_status = itr->second;

        if (q_status.Status == QUEST_STATUS_INCOMPLETE)
        {
            if (l_Quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_EXPLORATION_OR_EVENT) && !q_status.Explored)
                return false;

            if (l_Quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED) && q_status.Timer == 0)
                return false;

            for (QuestObjective l_Objective : l_Quest->QuestObjectives)
            {
                if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_AREATRIGGER)
                {

                }
                else if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_SPELL)
                {
                    if (!HasSpell(l_Objective.ObjectID))
                        return false;
                }
                else if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_FACTION_REP || l_Objective.Type == QUEST_OBJECTIVE_TYPE_FACTION_REP2)
                {
                    uint32 l_RepFactionID = l_Objective.ObjectID;

                    if (l_RepFactionID && GetReputationMgr().GetReputation(l_RepFactionID) < l_Objective.Amount)
                        return false;
                }
                else if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_MONEY)
                {
                    if (!HasEnoughMoney(-int64(l_Objective.Amount)))
                        return false;
                }
                else
                {
                    if (GetQuestObjectiveCounter(l_Objective.ID) < uint32(l_Objective.Amount))
                        return false;
                }
            }

            return true;
        }
    }
    return false;
}

bool Player::CanCompleteRepeatableQuest(const Quest * p_Quest)
{
    // Solve problem that player don't have the quest and try complete it.
    // if repeatable she must be able to complete event if player don't have it.
    // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
    if (!CanTakeQuest(p_Quest, false))
        return false;

    for (QuestObjective l_Objective : p_Quest->QuestObjectives)
    {
        if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_ITEM)
        {
            if (!HasItemCount(l_Objective.Amount, l_Objective.Amount))
                return false;
        }
    }

    if (!CanRewardQuest(p_Quest, false))
        return false;

    return true;
}

bool Player::CanRewardQuest(Quest const* p_Quest, bool msg)
{
    // not auto complete quest and not completed quest (only cheating case, then ignore without message)
    if (!p_Quest->IsDFQuest() && !p_Quest->IsAutoComplete() && !(p_Quest->GetFlags() & QUEST_FLAGS_AUTOCOMPLETE) && GetQuestStatus(p_Quest->GetQuestId()) != QUEST_STATUS_COMPLETE)
        return false;

    // daily quest can't be rewarded (25 daily quest already completed)
    if (!SatisfyQuestDay(p_Quest) || !SatisfyQuestWeek(p_Quest, true) || !SatisfyQuestMonth(p_Quest, true) || !SatisfyQuestSeasonal(p_Quest, true))
        return false;

    // rewarded and not repeatable quest (only cheating case, then ignore without message)
    if (GetQuestRewardStatus(p_Quest->GetQuestId()))
        return false;

    if (!SatisfyQuestSkill(p_Quest, msg))
        return false;

    for (QuestObjective l_Objective : p_Quest->QuestObjectives)
    {
        if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_ITEM && !(l_Objective.Flags & QuestObjectiveFlags::QUEST_OBJECTIVE_FLAG_UNK_4))
        {
            if (GetItemCount(l_Objective.ObjectID) < uint32(l_Objective.Amount))
            {
                if (msg)
                    SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL, l_Objective.ObjectID);

                return false;
            }
        }
        else if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_CURRENCY)
        {
            if (!HasCurrency(l_Objective.ObjectID, l_Objective.Amount))
                return false;
        }
        else if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_MONEY)
        {
            if (!HasEnoughMoney(uint64(l_Objective.Amount)))
                return false;
        }
    }

    return true;
}

bool Player::CanRewardQuest(Quest const* quest, uint32 p_Reward, bool msg)
{
    // prevent receive reward with quest items in bank or for not completed quest
    if (!CanRewardQuest(quest, msg))
        return false;

    /// - Quest have dynamic reward, skip legacy choice
    if (quest->GetQuestPackageID() != 0)
    {
        /// - Check if the reward is in dynamic reward list, and if player can take it (class/spec)
        for (QuestPackageItemEntry const* l_DynamicReward : quest->DynamicRewards)
        {
            if (l_DynamicReward->ItemId != p_Reward)
                continue;

            ItemTemplate const* l_ItemTemplate = sObjectMgr->GetItemTemplate(l_DynamicReward->ItemId);
            if (!l_ItemTemplate)
                return false;

            /// Hackfix, but fix lot of quests since the selection work client-side
            /// See quest 24970 with a hunter
            {
                /// - We have find the reward, check if player can store it
                ItemPosCountVec l_Dest;
                InventoryResult l_Result = CanStoreNewItem(NULL_BAG, NULL_SLOT, l_Dest, l_DynamicReward->ItemId, l_DynamicReward->Count);
                if (l_Result != EQUIP_ERR_OK)
                {
                    SendEquipError(l_Result, NULL, NULL, l_DynamicReward->ItemId);
                    return false;
                }

                return true;
            }

            uint32 l_Specialization = GetSpecializationId();
            if (!l_Specialization)
                l_Specialization = GetDefaultSpecId();

            switch (l_DynamicReward->Type)
            {
                case uint8(PackageItemRewardType::SpecializationReward):
                    if (!l_ItemTemplate->HasSpec((SpecIndex)l_Specialization, getLevel()))
                    {
                        GetSession()->SendNotification(LANG_NO_SPE_FOR_DYNAMIC_REWARD);
                        return false;
                    }
                    break;
                case uint8(PackageItemRewardType::ClassReward):
                    if (!l_ItemTemplate->HasClassSpec(getClass(), getLevel()))
                        return false;
                    break;
                case uint8(PackageItemRewardType::DefaultHiddenReward):                             ///< Yes, player can cheat to have it instead of his own specific item, but it's useless for him
                case uint8(PackageItemRewardType::NoRequire):
                    break;
                // Not implemented PackageItemRewardType
                default:
                    sLog->outError(LogFilterType::LOG_FILTER_PLAYER_ITEMS, "Not implemented PackageItemRewardType %u for quest %u", l_DynamicReward->Type, quest->GetQuestId());
                    continue;
            }

            /// - We have find the reward, check if player can store it
            ItemPosCountVec l_Dest;
            InventoryResult l_Result = CanStoreNewItem(NULL_BAG, NULL_SLOT, l_Dest, l_DynamicReward->ItemId, l_DynamicReward->Count);
            if (l_Result != EQUIP_ERR_OK)
            {
                SendEquipError(l_Result, NULL, NULL, l_DynamicReward->ItemId);
                return false;
            }
            return true;
        }
        
        if (p_Reward == 0)
            return true;
        
        return false;
    }

    if (quest->GetRewChoiceItemsCount() > 0)
    {
        if (quest->RewardChoiceItemId[p_Reward])
        {
            ItemPosCountVec dest;
            InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardChoiceItemId[p_Reward], quest->RewardChoiceItemCount[p_Reward]);
            if (res != EQUIP_ERR_OK)
            {
                SendEquipError(res, NULL, NULL, quest->RewardChoiceItemId[p_Reward]);
                return false;
            }
        }
    }

    if (quest->GetRewItemsCount() > 0)
    {
        for (uint32 i = 0; i < quest->GetRewItemsCount(); ++i)
        {
            if (quest->RewardItemId[i])
            {
                ItemPosCountVec dest;
                InventoryResult res = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, quest->RewardItemId[i], quest->RewardItemIdCount[i]);
                if (res != EQUIP_ERR_OK)
                {
                    SendEquipError(res, NULL, NULL, quest->RewardItemId[i]);
                    return false;
                }
            }
        }
    }

    return true;
}

void Player::AddQuest(Quest const* quest, Object* questGiver)
{
    uint16 log_slot = FindQuestSlot(0);

    if (log_slot >= MAX_QUEST_LOG_SIZE) // Player does not have any free slot in the quest log
        return;

    uint32 quest_id = quest->GetQuestId();

    // if not exist then created with set uState == NEW and rewarded=false
    QuestStatusData& questStatusData = m_QuestStatus[quest_id];

    // check for repeatable quests status reset
    questStatusData.Status = QUEST_STATUS_INCOMPLETE;
    questStatusData.Explored = false;

    for (QuestObjective l_Objective : quest->QuestObjectives)
    {
        if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_FACTION_REP || l_Objective.Type == QUEST_OBJECTIVE_TYPE_FACTION_REP2)
        {
            if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(l_Objective.ObjectID))
                GetReputationMgr().SetVisible(factionEntry);
        }

        // not all Quest Objective types need to be tracked, some such as reputation are handled/checked externally
        if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_SPELL
            || l_Objective.Type == QUEST_OBJECTIVE_TYPE_FACTION_REP
            || l_Objective.Type == QUEST_OBJECTIVE_TYPE_FACTION_REP2
            || l_Objective.Type == QUEST_OBJECTIVE_TYPE_MONEY
            || l_Objective.Type == QUEST_OBJECTIVE_TYPE_AREATRIGGER)
            continue;

        m_questObjectiveStatus.insert(std::make_pair(l_Objective.ID, uint32(0)));
    }

    GiveQuestSourceItem(quest);
    AdjustQuestReqItemCount(quest);

    uint32 qtime = 0;
    if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED))
    {
        uint32 limittime = quest->GetLimitTime();

        // shared timed quest
        if (questGiver && questGiver->IsPlayer())
            limittime = questGiver->ToPlayer()->getQuestStatusMap()[quest_id].Timer / IN_MILLISECONDS;

        AddTimedQuest(quest_id);
        questStatusData.Timer = limittime * IN_MILLISECONDS;
        qtime = static_cast<uint32>(time(NULL)) + limittime;
    }
    else
        questStatusData.Timer = 0;

    SetQuestSlot(log_slot, quest_id, qtime);

    m_QuestStatusSave[quest_id] = true;

    GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_QUEST, quest_id);

    //starting initial quest script
    if (questGiver && quest->GetQuestStartScript() != 0)
        GetMap()->ScriptsStart(sQuestStartScripts, quest->GetQuestStartScript(), questGiver, this);

    CheckSpellAreaOnQuestStatusChange(quest_id);

    PhaseUpdateData phaseUdateData;
    phaseUdateData.AddQuestUpdate(quest_id);

    phaseMgr.NotifyConditionChanged(phaseUdateData);

    UpdateForQuestWorldObjects();

    if (m_Garrison && IsInGarrison())
        m_Garrison->OnQuestStarted(quest);

    sScriptMgr->OnQuestAccept(this, quest);
}

void Player::CompleteQuest(uint32 quest_id)
{
    if (quest_id)
    {
        SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);

        uint16 log_slot = FindQuestSlot(quest_id);
        if (log_slot < MAX_QUEST_LOG_SIZE)
        {
            SetQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_0_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_1_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_2_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_3_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_4_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_5_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_6_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_7_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_8_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_9_COMPLETE);
            SetQuestSlotState(log_slot, QUEST_STATE_OBJ_10_COMPLETE);
        }

        if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id))
        {
            if (qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED))
                RewardQuest(qInfo, 0, this, false);
            else
                SendQuestComplete(qInfo);


            sScriptMgr->OnQuestComplete(this, qInfo);
        }

        if (Guild* l_Guild = GetGuild())
            l_Guild->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD, 1, 0, 0, nullptr, this);

    }
}

void Player::IncompleteQuest(uint32 quest_id)
{
    if (quest_id)
    {
        SetQuestStatus(quest_id, QUEST_STATUS_INCOMPLETE);

        uint16 log_slot = FindQuestSlot(quest_id);
        if (log_slot < MAX_QUEST_LOG_SIZE)
            RemoveQuestSlotState(log_slot, QUEST_STATE_COMPLETE);
    }
}

void Player::RewardQuest(Quest const* p_Quest, uint32 p_Reward, Object* p_QuestGiver, bool p_Announce)
{
    //this THING should be here to protect code from quest, which cast on player far teleport as a reward
    //should work fine, cause far teleport will be executed in Player::Update()
    SetCanDelayTeleport(true);

    uint32 l_QuestId = p_Quest->GetQuestId();

    for (auto l_Objective : p_Quest->QuestObjectives)
    {
        switch (l_Objective.Type)
        {
            case QUEST_OBJECTIVE_TYPE_ITEM:
            {
                if (!(l_Objective.Flags & QuestObjectiveFlags::QUEST_OBJECTIVE_FLAG_UNK_4))
                    DestroyItemCount(l_Objective.ObjectID, l_Objective.Amount, true);
                break;
            }
            case QUEST_OBJECTIVE_TYPE_CURRENCY:
            {
                ModifyCurrency(l_Objective.ObjectID, -int32(l_Objective.Amount));
                break;
            }
            case QUEST_OBJECTIVE_TYPE_MONEY:
            {
                ModifyMoney(-int64(l_Objective.Amount));
                break;
            }
            default:
                break;
        }
    }

    if (!p_Quest->HasFlag2(QUEST_FLAGS2_KEEP_ADDITIONAL_ITEMS))
    {
        for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
        {
            if (p_Quest->RequiredSourceItemId[i])
            {
                uint32 count = p_Quest->RequiredSourceItemCount[i];
                DestroyItemCount(p_Quest->RequiredSourceItemId[i], count ? count : 9999, true);
            }
        }
    }

    RemoveTimedQuest(l_QuestId);

    /// - Quest have dynamic reward, skip legacy choice
    if (p_Quest->GetQuestPackageID() != 0)
    {
        /// - Check if the reward is in dynamic reward list, and if player can take it (class/spec)
        for (QuestPackageItemEntry const* l_DynamicReward : p_Quest->DynamicRewards)
        {
            if (l_DynamicReward->ItemId != p_Reward)
                continue;

            ItemTemplate const* l_ItemTemplate = sObjectMgr->GetItemTemplate(l_DynamicReward->ItemId);
            if (!l_ItemTemplate)
                break;

            /*switch (l_DynamicReward->Type)
            {
                case uint8(PackageItemRewardType::SpecializationReward):
                {
                    if (!l_ItemTemplate->HasSpec((SpecIndex)GetSpecializationId(), getLevel()) && !l_ItemTemplate->HasClassSpec(getClass(), getLevel()))
                        continue;
                    break;
                }
                case uint8(PackageItemRewardType::ClassReward):
                    if (!l_ItemTemplate->HasClassSpec(getClass(), getLevel()))
                        continue;
                    break;
                case uint8(PackageItemRewardType::DefaultHiddenReward):                             ///< Yes, player can cheat to have it instead of his own specific item, but it's useless for him
                case uint8(PackageItemRewardType::NoRequire):
                    break;
                default:
                    continue;
            }*/

            ItemPosCountVec l_Dest;
            if (CanStoreNewItem(NULL_BAG, NULL_SLOT, l_Dest, l_DynamicReward->ItemId, l_DynamicReward->Count) == EQUIP_ERR_OK)
            {
                Item* l_Item = StoreNewItem(l_Dest, l_DynamicReward->ItemId, true, Item::GenerateItemRandomPropertyId(l_DynamicReward->ItemId));

                /// - If quest is WoD quest & item is stuff, there is a chance player get bonus on the item
                if (l_Item->IsStuffItem())
                {
                    AreaTableEntry const* l_AreaTable = GetAreaEntryByAreaID(p_Quest->GetZoneOrSort());
                    if (l_AreaTable != nullptr)
                    {
                        MapEntry const* l_Map = sMapStore.LookupEntry(l_AreaTable->ContinentID);
                        if (l_Map != nullptr
                            && l_Map->Expansion() == Expansion::EXPANSION_WARLORDS_OF_DRAENOR)
                        {
                            float l_Roll = frand(0.0f, 100.0f);
                            float l_Coeff = 1.0f;

                            if (GetGarrison())
                            {
                                bool l_Level1 = GetGarrison()->HasActiveBuilding(MS::Garrison::Buildings::DwarvenBunker_WarMill_Level1);
                                bool l_Level2 = GetGarrison()->HasActiveBuilding(MS::Garrison::Buildings::DwarvenBunker_WarMill_Level2);
                                bool l_Level3 = GetGarrison()->HasActiveBuilding(MS::Garrison::Buildings::DwarvenBunker_WarMill_Level3);

                                if (l_Level1 || l_Level2 || l_Level3)
                                    l_Coeff *= 2.0f;

                            }

                            //bool  l_SendDisplayToast = false;

                            // If item is uncommon & chance match, add uncommun to rare modifier
                            if (l_ItemTemplate->Quality == ItemQualities::ITEM_QUALITY_UNCOMMON
                                && l_Roll > (gQuestRewardBonusRareChanceRange[0] * l_Coeff) && l_Roll < (gQuestRewardBonusRareChanceRange[1] * l_Coeff))
                            {
                                l_Item->AddItemBonus((uint32)QuestRewardItemBonus::UncommunToRare);
                                //l_SendDisplayToast = true;
                            }

                            if (l_Roll > (gQuestRewardBonusEpicChanceRange[0] * l_Coeff) && l_Roll < (gQuestRewardBonusEpicChanceRange[1] * l_Coeff))
                            {
                                if (l_ItemTemplate->Quality == ItemQualities::ITEM_QUALITY_UNCOMMON)
                                {
                                    l_Item->AddItemBonus((uint32)QuestRewardItemBonus::UncommunToEpic);
                                    //l_SendDisplayToast = true;
                                }
                                else if (l_ItemTemplate->Quality == ItemQualities::ITEM_QUALITY_RARE)
                                {
                                    l_Item->AddItemBonus((uint32)QuestRewardItemBonus::RareToEpic);
                                    //l_SendDisplayToast = true;
                                }
                            }

                            /// - Look like the client automaticaly display the popup without send display toast if bonus is sended in SMSG_PUSH_ITEM_RESULT
                            //if (l_SendDisplayToast)
                                //SendDisplayToast(l_ItemTemplate->ItemId, l_DynamicReward->Count, DisplayToastMethod::DISPLAY_TOAST_METHOD_LOOT, TOAST_TYPE_NEW_ITEM, false, false, l_Item->GetAllItemBonuses());
                        }
                    }
                }

                SendNewItem(l_Item, l_DynamicReward->Count, true, false, false);
            }
            break;
        }
    }
    else
    {
        if (p_Quest->GetRewChoiceItemsCount() > 0)
        {
            if (uint32 itemId = p_Quest->RewardChoiceItemId[p_Reward])
            {
                ItemPosCountVec l_Dest;
                if (CanStoreNewItem(NULL_BAG, NULL_SLOT, l_Dest, itemId, p_Quest->RewardChoiceItemCount[p_Reward]) == EQUIP_ERR_OK)
                {
                    Item* l_Item = StoreNewItem(l_Dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
                    SendNewItem(l_Item, p_Quest->RewardChoiceItemCount[p_Reward], true, false);
                }
            }
        }

        if (p_Quest->GetRewItemsCount() > 0)
        {
            for (uint32 l_I = 0; l_I < p_Quest->GetRewItemsCount(); ++l_I)
            {
                if (uint32 l_ItemId = p_Quest->RewardItemId[l_I])
                {
                    ItemPosCountVec l_Dest;
                    if (CanStoreNewItem(NULL_BAG, NULL_SLOT, l_Dest, l_ItemId, p_Quest->RewardItemIdCount[l_I]) == EQUIP_ERR_OK)
                    {
                        Item* l_Item = StoreNewItem(l_Dest, l_ItemId, true, Item::GenerateItemRandomPropertyId(l_ItemId));
                        SendNewItem(l_Item, p_Quest->RewardItemIdCount[l_I], true, false);
                    }
                }
            }
        }
    }

    if (p_Quest->GetRewCurrencyCount() > 0)
    {
        for (uint32 i = 0; i < p_Quest->GetRewCurrencyCount(); ++i)
        {
            if (uint32 currencyId = p_Quest->RewardCurrencyId[i])
            {
                CurrencyTypesEntry const* currency = sCurrencyTypesStore.LookupEntry(currencyId);
                if (uint32 countCurrency = p_Quest->RewardCurrencyCount[i])
                {
                    if (currency->Flags & CURRENCY_FLAG_HIGH_PRECISION)
                        countCurrency *= 100;
                    ModifyCurrency(currencyId, countCurrency);
                }
            }
        }
    }

    RewardReputation(p_Quest);
    RewardGuildReputation(p_Quest);

    uint16 log_slot = FindQuestSlot(l_QuestId);
    if (log_slot < MAX_QUEST_LOG_SIZE)
        SetQuestSlot(log_slot, 0);

    bool rewarded = (m_RewardedQuests.find(l_QuestId) != m_RewardedQuests.end());

    float QuestXpRate = 1;

    if (GetPersonnalXpRate())
        QuestXpRate = GetPersonnalXpRate();
    else
        QuestXpRate = sWorld->getRate(RATE_XP_QUEST);

    // Not give XP in case already completed once repeatable quest
    uint32 XP = rewarded ? 0 : uint32(p_Quest->XPValue(this) * QuestXpRate);

    // handle SPELL_AURA_MOD_XP_QUEST_PCT auras
    Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_QUEST_PCT);
    for (Unit::AuraEffectList::const_iterator l_I = ModXPPctAuras.begin(); l_I != ModXPPctAuras.end(); ++l_I)
        AddPct(XP, (*l_I)->GetAmount());

    //if (GetSession()->IsPremium())
    //    XP *= sWorld->getRate(RATE_XP_QUEST_PREMIUM);

    uint32 moneyRew = 0;
    if (getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
        GiveXP(XP, NULL);
    else
        moneyRew = uint32(p_Quest->GetRewMoneyMaxLevel() * sWorld->getRate(RATE_DROP_MONEY));

    moneyRew += p_Quest->GetRewMoney();
    ModifyMoney(moneyRew);

    if (moneyRew > 0)
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, uint32(moneyRew));

    // honor reward
    if (uint32 honor = p_Quest->CalculateHonorGain(getLevel()))
        RewardHonor(NULL, 0, honor);

    // title reward
    if (p_Quest->GetCharTitleId())
    {
        if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(p_Quest->GetCharTitleId()))
            SetTitle(titleEntry);
    }

    if (uint32 talents = p_Quest->GetBonusTalents())
    {
        AddQuestRewardedTalentCount(talents);
        InitTalentForLevel();
    }

    // Send reward mail
    if (uint32 mail_template_id = p_Quest->GetRewMailTemplateId())
    {
        //- TODO: Poor design of mail system
        SQLTransaction trans = CharacterDatabase.BeginTransaction();
        MailDraft(mail_template_id).SendMailTo(trans, this, p_QuestGiver, MAIL_CHECK_MASK_HAS_BODY, p_Quest->GetRewMailDelaySecs());
        CharacterDatabase.CommitTransaction(trans);
    }

    if (p_Quest->IsDaily() || p_Quest->IsDFQuest())
    {
        SetDailyQuestStatus(l_QuestId);
        if (p_Quest->IsDaily())
        {
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, l_QuestId);
            UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY, l_QuestId);
        }
    }
    else if (p_Quest->IsWeekly())
        SetWeeklyQuestStatus(l_QuestId);
    else if (p_Quest->IsMonthly())
        SetMonthlyQuestStatus(l_QuestId);
    else if (p_Quest->IsSeasonal())
        SetSeasonalQuestStatus(l_QuestId);

    m_RewardedQuests.insert(l_QuestId);
    m_RewardedQuestsSave[l_QuestId] = true;

    PhaseUpdateData phaseUdateData;
    phaseUdateData.AddQuestUpdate(l_QuestId);
    phaseMgr.NotifyConditionChanged(phaseUdateData);

    // Must come after the insert in m_RewardedQuests because of spell_area check
    RemoveActiveQuest(l_QuestId);

    phaseUdateData.AddQuestUpdate(l_QuestId);

    phaseMgr.NotifyConditionChanged(phaseUdateData);

    // StoreNewItem, mail reward, etc. save data directly to the database
    // to prevent exploitable data desynchronisation we save the quest status to the database too
    // (to prevent rewarding this quest another time while rewards were already given out)
    SQLTransaction trans = SQLTransaction(NULL);
    _SaveQuestStatus(trans);

    if (p_Announce)
        SendQuestReward(p_Quest, XP, p_QuestGiver);

    // cast spells after mark quest complete (some spells have quest completed state requirements in spell_area data)
    if (p_Quest->GetRewSpellCast() > 0)
        CastSpell(this, p_Quest->GetRewSpellCast(), true);
    else if (p_Quest->GetRewSpell() > 0)
        CastSpell(this, p_Quest->GetRewSpell(), true);

    sScriptMgr->OnQuestReward(this, p_Quest);

    if (m_Garrison && IsInGarrison())
        m_Garrison->OnQuestReward(p_Quest);

    if (p_Quest->GetZoneOrSort() > 0)
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, p_Quest->GetZoneOrSort());
    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, p_Quest->GetQuestId());

    if (uint32 l_QuestBit = GetQuestUniqueBitFlag(l_QuestId))
        SetQuestBit(l_QuestBit, true);

    //lets remove flag for delayed teleports
    SetCanDelayTeleport(false);
}

void Player::FailQuest(uint32 questId)
{
    if (Quest const* quest = sObjectMgr->GetQuestTemplate(questId))
    {
        SetQuestStatus(questId, QUEST_STATUS_FAILED);

        uint16 log_slot = FindQuestSlot(questId);

        if (log_slot < MAX_QUEST_LOG_SIZE)
        {
            SetQuestSlotTimer(log_slot, 1);
            SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
        }

        if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED))
        {
            QuestStatusData& q_status = m_QuestStatus[questId];

            RemoveTimedQuest(questId);
            q_status.Timer = 0;

            SendQuestTimerFailed(questId);
        }
        else
            SendQuestFailed(questId);

        // Destroy quest items on quest failure.
        if (quest->GetQuestObjectiveCountType(QUEST_OBJECTIVE_TYPE_ITEM))
        {
            for (QuestObjective l_Objective : quest->QuestObjectives)
            {
                if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_ITEM)
                {
                    DestroyItemCount(l_Objective.ObjectID, l_Objective.Amount, true, true);
                }
            }
        }

        for (uint8 i = 0; i < QUEST_SOURCE_ITEM_IDS_COUNT; ++i)
            if (quest->RequiredSourceItemId[i] > 0 && quest->RequiredSourceItemCount[i] > 0)
                // Destroy items received during the quest.
                DestroyItemCount(quest->RequiredSourceItemId[i], quest->RequiredSourceItemCount[i], true, true);
    }
}

bool Player::SatisfyQuestSkill(Quest const* qInfo, bool msg) const
{
    uint32 skill = qInfo->GetRequiredSkill();

    // skip 0 case RequiredSkill
    if (skill == 0)
        return true;

    uint32 skill_value = qInfo->GetRequiredSkillValue();
    if (skill_value == 0)
        skill_value = 1;

    // check skill value
    if (GetSkillValue(skill) < skill_value)
    {
        if (msg)
        {
            SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

            if (m_IsDebugQuestLogs && GetSession())
                ChatHandler(GetSession()).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_MISSING_SKILL);
        }

        return false;
    }

    return true;
}

bool Player::SatisfyQuestLevel(Quest const* qInfo, bool msg)
{
    if (getLevel() < qInfo->GetMinLevel())
    {
        if (msg)
        {
            SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_LOW_LEVEL);

            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_TOO_LOW_LVL);
        }

        return false;
    }
    else if (qInfo->GetMaxLevel() > 0 && getLevel() > qInfo->GetMaxLevel())
    {
        if (msg)
        {
            SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ); // There doesn't seem to be a specific response for too high player level

            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_TOO_HIGH_LVL);
        }

        return false;
    }
    return true;
}

bool Player::SatisfyQuestLog(bool msg)
{
    // exist free slot
    if (FindQuestSlot(0) < MAX_QUEST_LOG_SIZE)
        return true;

    if (msg)
    {
        WorldPacket data(SMSG_QUEST_LOG_FULL, 0);
        GetSession()->SendPacket(&data);

        if (m_IsDebugQuestLogs)
            ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_QUEST_LOG);
    }

    return false;
}

bool Player::SatisfyQuestPreviousQuest(Quest const* qInfo, bool msg)
{
    // No previous quest (might be first quest in a series)
    if (qInfo->prevQuests.empty())
        return true;

    for (Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter)
    {
        uint32 prevId = abs(*iter);

        Quest const* qPrevInfo = sObjectMgr->GetQuestTemplate(prevId);

        if (qPrevInfo)
        {
            // If any of the positive previous quests completed, return true
            if (*iter > 0 && m_RewardedQuests.find(prevId) != m_RewardedQuests.end())
            {
                // skip one-from-all exclusive group
                if (qPrevInfo->GetExclusiveGroup() >= 0)
                    return true;

                // each-from-all exclusive group (< 0)
                // can be start if only all quests in prev quest exclusive group completed and rewarded
                ObjectMgr::ExclusiveQuestGroups::iterator iter2 = sObjectMgr->mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
                ObjectMgr::ExclusiveQuestGroups::iterator end  = sObjectMgr->mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());

                ASSERT(iter2 != end);                         // always must be found if qPrevInfo->ExclusiveGroup != 0

                for (; iter2 != end; ++iter2)
                {
                    uint32 exclude_Id = iter2->second;

                    // skip checked quest id, only state of other quests in group is interesting
                    if (exclude_Id == prevId)
                        continue;

                    // alternative quest from group also must be completed and rewarded(reported)
                    if (m_RewardedQuests.find(exclude_Id) == m_RewardedQuests.end())
                    {
                        if (msg)
                        {
                            SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

                            if (m_IsDebugQuestLogs)
                                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_EXCL_GRP_ALT_COMP);
                        }

                        return false;
                    }
                }
                return true;
            }

            // If any of the negative previous quests active, return true
            if (*iter < 0 && GetQuestStatus(prevId) != QUEST_STATUS_NONE)
            {
                // skip one-from-all exclusive group
                if (qPrevInfo->GetExclusiveGroup() >= 0)
                    return true;

                // each-from-all exclusive group (< 0)
                // can be start if only all quests in prev quest exclusive group active
                ObjectMgr::ExclusiveQuestGroups::iterator iter2 = sObjectMgr->mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
                ObjectMgr::ExclusiveQuestGroups::iterator end   = sObjectMgr->mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());

                ASSERT(iter2 != end);                         // always must be found if qPrevInfo->ExclusiveGroup != 0

                for (; iter2 != end; ++iter2)
                {
                    uint32 exclude_Id = iter2->second;

                    // skip checked quest id, only state of other quests in group is interesting
                    if (exclude_Id == prevId)
                        continue;

                    // alternative quest from group also must be active
                    if (GetQuestStatus(exclude_Id) != QUEST_STATUS_NONE)
                    {
                        if (msg)
                        {
                            SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

                            if (m_IsDebugQuestLogs)
                                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_EXCL_GRP_ALT_ACTIVE);
                        }

                        return false;
                    }
                }
                return true;
            }
        }
    }

    // Has only positive prev. quests in non-rewarded state
    // and negative prev. quests in non-active state
    if (msg)
    {
        SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

        if (m_IsDebugQuestLogs)
            ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_PREV_QUEST);
    }

    return false;
}

bool Player::SatisfyQuestTeam(Quest const* qInfo)
{
    int8 reqteam = qInfo->GetRequiredTeam();

    if (reqteam < 0)
        return true;

    if (reqteam == GetTeamId())
        return true;

    if (m_IsDebugQuestLogs)
        ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_FACTION);

    return false;
}

bool Player::SatisfyQuestClass(Quest const* qInfo, bool msg) const
{
    int32 reqClass = qInfo->GetRequiredClasses();

    if (!reqClass)
        return true;

    if (reqClass > 0)
    {
        // Positive = Only specified
        if ((reqClass & getClassMask()) == 0)
        {
            if (msg)
            {
                SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

                if (m_IsDebugQuestLogs && GetSession())
                    ChatHandler(GetSession()).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_CLASS);
            }

            return false;
        }
    }
    else
    {
        // Negative = All except specified
        reqClass = -reqClass;

        if (reqClass & getClassMask())
        {
            if (msg)
            {
                SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

                if (m_IsDebugQuestLogs && GetSession())
                    ChatHandler(GetSession()).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_CLASS);
            }

            return false;
        }
    }

    return true;
}

bool Player::SatisfyQuestRace(Quest const* qInfo, bool msg)
{
    int32 reqraces = qInfo->GetRequiredRaces();
    if (!reqraces)
        return true;

    if (reqraces > 0)
    {
        // Positive = Only specified
        if ((reqraces & getRaceMask()) == 0)
        {
            if (msg)
            {
                SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE);

                if (m_IsDebugQuestLogs)
                    ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_RACE);
            }

            return false;
        }
    }
    else
    {
        // Negative = All except specified
        reqraces = -reqraces;

        if (reqraces & getRaceMask())
        {
            if (msg)
            {
                SendCanTakeQuestResponse(INVALIDREASON_QUEST_FAILED_WRONG_RACE);

                if (m_IsDebugQuestLogs)
                    ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_RACE);
            }

            return false;
        }
    }

    return true;
}

bool Player::SatisfyQuestReputation(Quest const* qInfo, bool msg)
{
    uint32 fIdMin = qInfo->GetRequiredMinRepFaction();      //Min required rep
    if (fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
    {
        if (msg)
        {
            SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_MIN_REP);
        }

        return false;
    }

    uint32 fIdMax = qInfo->GetRequiredMaxRepFaction();      //Max required rep
    if (fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
    {
        if (msg)
        {
            SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_MAX_REP);
        }

        return false;
    }

    // ReputationObjective2 does not seem to be an objective requirement but a requirement
    // to be able to accept the quest

    if (!qInfo->GetQuestObjectiveCountType(QUEST_OBJECTIVE_TYPE_FACTION_REP2))
        return true;

    for (QuestObjective l_Objective : qInfo->QuestObjectives)
    {
        if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_FACTION_REP2 && GetReputationMgr().GetReputation(l_Objective.ObjectID) >= l_Objective.Amount)
        {
            if (msg)
            {
                SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

                if (m_IsDebugQuestLogs)
                    ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_OBJ_REP);
            }

            return false;
        }
    }

    return true;
}

bool Player::SatisfyQuestStatus(Quest const* p_QInfo, bool p_Msg)
{
    if (GetQuestStatus(p_QInfo->GetQuestId()) != QUEST_STATUS_NONE)
    {
        if (p_Msg)
        {
            SendCanTakeQuestResponse(INVALIDREASON_QUEST_ALREADY_ON);

            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_STATUS);
        }

        return false;
    }
    return true;
}

bool Player::SatisfyQuestConditions(Quest const* qInfo, bool msg)
{
    if (!sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_QUEST_ACCEPT, qInfo->GetQuestId(), this))
    {
        if (msg)
        {
            SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_CONDITION);
        }

        sLog->outDebug(LOG_FILTER_CONDITIONSYS, "Player::SatisfyQuestConditions: conditions not met for quest %u", qInfo->GetQuestId());

        return false;
    }
    return true;
}

bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
{
    if (!m_timedquests.empty() && qInfo->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED))
    {
        if (msg)
        {
            SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);

            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WRONG_TIME);
        }

        return false;
    }
    return true;
}

bool Player::SatisfyQuestExclusiveGroup(Quest const* qInfo, bool msg)
{
    // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
    if (qInfo->GetExclusiveGroup() <= 0)
        return true;

    ObjectMgr::ExclusiveQuestGroups::iterator iter = sObjectMgr->mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
    ObjectMgr::ExclusiveQuestGroups::iterator end  = sObjectMgr->mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());

    //ASSERT(iter != end);                                      // always must be found if qInfo->ExclusiveGroup != 0

    for (; iter != end; ++iter)
    {
        uint32 exclude_Id = iter->second;

        // skip checked quest id, only state of other quests in group is interesting
        if (exclude_Id == qInfo->GetQuestId())
            continue;

        // not allow have daily quest if daily quest from exclusive group already recently completed
        Quest const* Nquest = sObjectMgr->GetQuestTemplate(exclude_Id);
        if (!SatisfyQuestDay(Nquest) || !SatisfyQuestWeek(Nquest, false) || !SatisfyQuestSeasonal(Nquest,false))
        {
            if (msg)
            {
                SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

                if (m_IsDebugQuestLogs)
                    ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_DOUBLE_EXCL);
            }

            return false;
        }

        // alternative quest already started or completed - but don't check rewarded states if both are repeatable
        if (GetQuestStatus(exclude_Id) != QUEST_STATUS_NONE || (!(qInfo->IsRepeatable() && Nquest->IsRepeatable()) && (m_RewardedQuests.find(exclude_Id) != m_RewardedQuests.end())))
        {
            if (msg)
            {
                SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

                if (m_IsDebugQuestLogs)
                    ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_ALT_QUEST);
            }

            return false;
        }
    }
    return true;
}

bool Player::SatisfyQuestNextChain(Quest const* qInfo, bool msg)
{
    uint32 nextQuest = qInfo->GetNextQuestInChain();
    if (!nextQuest)
        return true;

    // next quest in chain already started or completed
    if (GetQuestStatus(nextQuest) != QUEST_STATUS_NONE) // GetQuestStatus returns QUEST_STATUS_COMPLETED for rewarded quests
    {
        if (msg)
        {
            SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_CHAIN_NEXT);
        }

        return false;
    }

    // check for all quests further up the chain
    // only necessary if there are quest chains with more than one quest that can be skipped
    //return SatisfyQuestNextChain(qInfo->GetNextQuestInChain(), msg);
    return true;
}

bool Player::SatisfyQuestPrevChain(Quest const* qInfo, bool msg)
{
    // No previous quest in chain
    if (qInfo->prevChainQuests.empty())
        return true;

    for (Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter)
    {
        QuestStatusMap::const_iterator itr = m_QuestStatus.find(*iter);

        // If any of the previous quests in chain active, return false
        if (itr != m_QuestStatus.end() && itr->second.Status != QUEST_STATUS_NONE)
        {
            if (msg)
            {
                SendCanTakeQuestResponse(INVALIDREASON_DONT_HAVE_REQ);

                if (m_IsDebugQuestLogs)
                    ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_CHAIN_PREV);
            }

            return false;
        }

        // check for all quests further down the chain
        // only necessary if there are quest chains with more than one quest that can be skipped
        //if (!SatisfyQuestPrevChain(prevId, msg))
        //    return false;
    }

    // No previous quest in chain active
    return true;
}

bool Player::SatisfyQuestDay(Quest const* qInfo)
{
    if (!qInfo->IsDaily() && !qInfo->IsDFQuest())
        return true;

    for (auto id : m_dailyQuestStorage)
    {
        if (qInfo->GetQuestId() == id)
        {
            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_DAILY_DONE);

            return false;
        }
    }

    if (qInfo->IsDFQuest())
    {
        if (!m_DFQuests.empty())
        {
            if (m_IsDebugQuestLogs)
                ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_DF_DAILY);

            return false;
        }

        return true;
    }

    return true;
}

bool Player::SatisfyQuestWeek(Quest const* qInfo, bool /*msg*/)
{
    if (!qInfo->IsWeekly() || m_weeklyquests.empty())
        return true;


    if (m_weeklyquests.find(qInfo->GetQuestId()) == m_weeklyquests.end())
        return true;

    /// if not found in cooldown list
    if (m_IsDebugQuestLogs)
        ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_WEEKLY_DONE);

    return false;
}

bool Player::SatisfyQuestSeasonal(Quest const* qInfo, bool /*msg*/)
{
    if (!qInfo->IsSeasonal() || m_seasonalquests.empty())
        return true;

    uint16 l_EventId = sGameEventMgr->GetEventIdForQuest(qInfo);
    if (m_seasonalquests.find(l_EventId) == m_seasonalquests.end() || m_seasonalquests[l_EventId].empty())
        return true;

    if (m_seasonalquests[l_EventId].find(qInfo->GetQuestId()) == m_seasonalquests[l_EventId].end())
        return true;

    /// if not found in cooldown list
    if (m_IsDebugQuestLogs)
        ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_SEASONNAL_DONE);

    return false;
}

bool Player::SatisfyQuestMonth(Quest const* qInfo, bool /*msg*/)
{
    if (!qInfo->IsMonthly() || m_monthlyquests.empty())
        return true;

    if (m_monthlyquests.find(qInfo->GetQuestId()) == m_monthlyquests.end())
        return true;

    /// if not found in cooldown list
    if (m_IsDebugQuestLogs)
        ChatHandler(this).PSendSysMessage(LANG_DEBUG_QUEST_LOGS_MONTHLY_DONE);

    return false;
}

bool Player::GiveQuestSourceItem(Quest const* quest)
{
    uint32 srcitem = quest->GetSrcItemId();
    if (srcitem > 0)
    {
        ItemPosCountVec dest;
        InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, srcitem, QUEST_SOURCE_ITEM_COUNT);
        if (msg == EQUIP_ERR_OK)
        {
            Item* item = StoreNewItem(dest, srcitem, true);
            SendNewItem(item, QUEST_SOURCE_ITEM_COUNT, true, false);
            return true;
        }
        // player already have max amount required item, just report success
        else if (msg == EQUIP_ERR_ITEM_MAX_COUNT)
            return true;
        else
            SendEquipError(msg, NULL, NULL, srcitem);
        return false;
    }

    return true;
}

bool Player::TakeQuestSourceItem(uint32 questId, bool msg)
{
    Quest const* quest = sObjectMgr->GetQuestTemplate(questId);
    if (quest)
    {
        uint32 srcItemId = quest->GetSrcItemId();
        ItemTemplate const* item = sObjectMgr->GetItemTemplate(srcItemId);

        if (srcItemId > 0)
        {
            // exist two cases when destroy source quest item not possible:
            // a) non un-equippable item (equipped non-empty bag, for example)
            // b) when quest is started from an item and item also is needed in
            // the end as RequiredItemId
            InventoryResult res = CanUnequipItems(srcItemId, QUEST_SOURCE_ITEM_COUNT);
            if (res != EQUIP_ERR_OK)
            {
                if (msg)
                    SendEquipError(res, NULL, NULL, srcItemId);
                return false;
            }

            if (!quest->GetQuestObjectiveCountType(QUEST_OBJECTIVE_TYPE_ITEM))
                return true;

            bool destroyItem = true;

            for (QuestObjective l_Objective : quest->QuestObjectives)
            {
                if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_ITEM && item->StartQuest == questId && srcItemId == (uint32)l_Objective.ObjectID)
                    destroyItem = false;
            }

            if (destroyItem)
                DestroyItemCount(srcItemId, QUEST_SOURCE_ITEM_COUNT, true, true);
        }
    }

    return true;
}

bool Player::GetQuestRewardStatus(uint32 quest_id) const
{
    Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
    if (qInfo)
    {
        // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
        if (!qInfo->IsRepeatable())
            return m_RewardedQuests.find(quest_id) != m_RewardedQuests.end();

        return false;
    }
    return false;
}

QuestStatus Player::GetQuestStatus(uint32 quest_id) const
{
    if (quest_id)
    {
        QuestStatusMap::const_iterator itr = m_QuestStatus.find(quest_id);
        if (itr != m_QuestStatus.end())
            return itr->second.Status;

        if (Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id))
            if (!qInfo->IsRepeatable() && m_RewardedQuests.find(quest_id) != m_RewardedQuests.end())
                return QUEST_STATUS_REWARDED;
    }
    return QUEST_STATUS_NONE;
}

bool Player::CanShareQuest(uint32 quest_id) const
{
    Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);
    if (qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE))
    {
        QuestStatusMap::const_iterator itr = m_QuestStatus.find(quest_id);
        if (itr != m_QuestStatus.end())
            return itr->second.Status == QUEST_STATUS_INCOMPLETE;
    }
    return false;
}

void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
{
    if (sObjectMgr->GetQuestTemplate(quest_id))
    {
        m_QuestStatus[quest_id].Status = status;
        m_QuestStatusSave[quest_id] = true;
    }

    CheckSpellAreaOnQuestStatusChange(quest_id);

    PhaseUpdateData phaseUdateData;
    phaseUdateData.AddQuestUpdate(quest_id);

    phaseMgr.NotifyConditionChanged(phaseUdateData);

    UpdateForQuestWorldObjects();
}

void Player::RemoveActiveQuest(uint32 quest_id)
{
    QuestStatusMap::iterator itr = m_QuestStatus.find(quest_id);
    if (itr != m_QuestStatus.end())
    {
        m_QuestStatus.erase(itr);
        m_QuestStatusSave[quest_id] = false;

        const Quest * l_Quest = sObjectMgr->GetQuestTemplate(quest_id);

        if (l_Quest)
        {
// Not sure, need to find real flag value (LANG_CANT_ABANDON_QUEST_FLAGGED undefined in trinity_string)
//             if ((l_Quest->GetFlags2() & QUEST_FLAGS2_NO_ABANDON_ON_ANY_OBJECTIVE_COMPLETE) != 0)
//             {
//                 for (QuestObjective l_Objective : l_Quest->QuestObjectives)
//                 {
//                     if (m_questObjectiveStatus[l_Objective.ID] == l_Objective.Amount)
//                     {
//                         if (GetSession())
//                             GetSession()->SendNotification(LANG_CANT_ABANDON_QUEST_FLAGGED);
//
//                         return;
//                     }
//                 }
//             }

            for (QuestObjective l_Objective : l_Quest->QuestObjectives)
            {
                m_questObjectiveStatus[l_Objective.ID] = 0;

                if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_ITEM && !(l_Objective.Flags & QuestObjectiveFlags::QUEST_OBJECTIVE_FLAG_UNK_4))
                    DestroyItemCount(l_Objective.ObjectID, l_Objective.Amount, true);
            }
        }

        CheckSpellAreaOnQuestStatusChange(quest_id);

        PhaseUpdateData phaseUdateData;
        phaseUdateData.AddQuestUpdate(quest_id);

        phaseMgr.NotifyConditionChanged(phaseUdateData);

        if (m_Garrison && IsInGarrison())
            m_Garrison->OnQuestAbandon(l_Quest);

        if (!IsQuestRewarded(quest_id))
            sScriptMgr->OnQuestAbandon(this, l_Quest);

        return;
    }
}

void Player::RemoveRewardedQuest(uint32 p_QuestId)
{
    RewardedQuestSet::iterator rewItr = m_RewardedQuests.find(p_QuestId);
    if (rewItr != m_RewardedQuests.end())
    {
        m_RewardedQuests.erase(rewItr);
        m_RewardedQuestsSave[p_QuestId] = false;

        PhaseUpdateData phaseUdateData;
        phaseUdateData.AddQuestUpdate(p_QuestId);

        phaseMgr.NotifyConditionChanged(phaseUdateData);

        if (uint32 l_QuestBit = GetQuestUniqueBitFlag(p_QuestId))
            SetQuestBit(l_QuestBit, false);
    }
}

// not used in Trinity, but used in scripting code
uint16 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
{
    Quest const* qInfo = sObjectMgr->GetQuestTemplate(quest_id);

    if (!qInfo)
        return 0;

    for (QuestObjective l_Objective : qInfo->QuestObjectives)
    {
        if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_NPC && l_Objective.ObjectID == entry)
        {
            return GetQuestObjectiveCounter(l_Objective.ID);
        }
    }

    return 0;
}

void Player::AreaExploredOrEventHappens(uint32 questId)
{
    if (questId)
    {
        uint16 log_slot = FindQuestSlot(questId);
        if (log_slot < MAX_QUEST_LOG_SIZE)
        {
            QuestStatusData& q_status = m_QuestStatus[questId];

            if (!q_status.Explored)
            {
                q_status.Explored = true;
                m_QuestStatusSave[questId] = true;
            }
        }
        if (CanCompleteQuest(questId))
            CompleteQuest(questId);
    }
}

void Player::AdjustQuestReqItemCount(Quest const* quest)
{
    if (!quest->GetQuestObjectiveCountType(QUEST_OBJECTIVE_TYPE_ITEM))
        return;

    for (QuestObjective l_Objective : quest->QuestObjectives)
    {
        if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_ITEM)
        {
            m_questObjectiveStatus[l_Objective.ID] = std::min(GetItemCount(l_Objective.ObjectID, true), uint32(l_Objective.Amount));
            m_QuestStatusSave[quest->GetQuestId()] = true;
        }
    }
}

uint16 Player::FindQuestSlot(uint32 quest_id) const
{
    for (uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
        if (GetQuestSlotQuestId(i) == quest_id)
            return i;

    return MAX_QUEST_LOG_SIZE;
}

//not used in Trinityd, function for external script library
void Player::GroupEventHappens(uint32 questId, WorldObject const* pEventObject)
{
    if (Group* group = GetGroup())
    {
        for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
        {
            Player* player = itr->getSource();

            // for any leave or dead (with not released body) group member at appropriate distance
            if (player && player->IsAtGroupRewardDistance(pEventObject) && !player->GetCorpse())
                player->AreaExploredOrEventHappens(questId);
        }
    }
    else
        AreaExploredOrEventHappens(questId);
}

void Player::ItemAddedQuestCheck(uint32 entry, uint32 count)
{
    for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
    {
        uint32 questid = GetQuestSlotQuestId(i);
        if (questid == 0)
            continue;

        QuestStatusData& q_status = m_QuestStatus[questid];

        if (q_status.Status != QUEST_STATUS_INCOMPLETE)
            continue;

        Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
        if (!qInfo)
            continue;

        for (QuestObjective l_Objective : qInfo->QuestObjectives)
        {
            if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_ITEM && (uint32)l_Objective.ObjectID == entry)
            {
                uint32 currentCounter = GetQuestObjectiveCounter(l_Objective.ID);
                uint32 requiredCounter = uint32(l_Objective.Amount);

                if (currentCounter < requiredCounter)
                {
                    uint16 addCount = currentCounter + count <= requiredCounter ? count : requiredCounter - currentCounter;
                    m_questObjectiveStatus[l_Objective.ID] += addCount;
                    m_QuestStatusSave[questid] = true;

                    SendQuestUpdateAddCredit(qInfo, l_Objective, ObjectGuid(0), currentCounter, addCount);
                }

                if (CanCompleteQuest(questid))
                    CompleteQuest(questid);

                return;
            }
        }
    }

    UpdateForQuestWorldObjects();
}

void Player::ItemRemovedQuestCheck(int32 entry, uint32 count)
{
    for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
    {
        uint32 questid = GetQuestSlotQuestId(i);

        if (!questid)
            continue;

        QuestStatusData& questStatus = m_QuestStatus[questid];
        Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);

        if (!qInfo)
            continue;

        if (!qInfo->GetQuestObjectiveCountType(QUEST_OBJECTIVE_TYPE_ITEM))
            continue;

        for (QuestObjective l_Objective : qInfo->QuestObjectives)
        {
            if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_ITEM && l_Objective.ObjectID == entry)
            {
                uint32 currentCounter = questStatus.Status != QUEST_STATUS_COMPLETE ? GetQuestObjectiveCounter(l_Objective.ID) : GetItemCount(entry, true);
                uint32 requiredCounter = uint32(l_Objective.Amount);

                if (currentCounter < requiredCounter)
                {
                    uint16 remainingItems = currentCounter <= requiredCounter ? count : count + requiredCounter - currentCounter;

                    m_questObjectiveStatus[l_Objective.ID] = (currentCounter <= remainingItems) ? 0 : currentCounter - remainingItems;
                    m_QuestStatusSave[questid] = true;

                    IncompleteQuest(questid);
                }

                break;
            }
        }
    }

    UpdateForQuestWorldObjects();
}

void Player::KilledMonster(CreatureTemplate const* cInfo, uint64 guid)
{
    if (cInfo->Entry)
        KilledMonsterCredit(cInfo->Entry, guid);

    for (uint8 i = 0; i < MAX_KILL_CREDIT; ++i)
        if (cInfo->KillCredit[i])
            KilledMonsterCredit(cInfo->KillCredit[i], 0);
}

void Player::KilledMonsterCredit(uint32 entry, uint64 guid)
{
    uint16 addkillcount = 1;
    uint32 real_entry = entry;
    if (guid)
    {
        Creature* killed = GetMap()->GetCreature(guid);
        if (killed && killed->GetEntry())
            real_entry = killed->GetEntry();
    }

    GetAchievementMgr().StartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_CREATURE, real_entry);   // MUST BE CALLED FIRST
    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, real_entry, addkillcount, 0, guid ? GetMap()->GetCreature(guid) : NULL);

    for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
    {
        uint32 questid = GetQuestSlotQuestId(i);
        if (!questid)
            continue;

        Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
        if (!qInfo)
            continue;
        // just if !ingroup || !noraidgroup || raidgroup
        QuestStatusData& q_status = m_QuestStatus[questid];
        if (q_status.Status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid()))
        {
            for (QuestObjective l_Objective : qInfo->QuestObjectives)
            {
                if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_NPC && l_Objective.ObjectID == (int32)real_entry)
                {
                    if (MS::Garrison::Manager* l_GarrisonMgr = GetGarrison())
                    {
                        if (!l_GarrisonMgr->CheckGarrisonStablesQuestsConditions(questid, this))
                            continue;
                    }

                    uint32 currentCounter = GetQuestObjectiveCounter(l_Objective.ID);
                    if (currentCounter < uint32(l_Objective.Amount))
                    {
                        m_questObjectiveStatus[l_Objective.ID] += addkillcount;
                        m_QuestStatusSave[questid] = true;
                        SendQuestUpdateAddCredit(qInfo, l_Objective, guid, currentCounter, addkillcount);
                    }

                    if ((uint32)l_Objective.Amount == m_questObjectiveStatus[l_Objective.ID])
                        sScriptMgr->OnObjectiveValidate(this, questid, l_Objective.ID);

                    if (CanCompleteQuest(questid))
                        CompleteQuest(questid);

                    break;
                }
            }
        }
    }
}

void Player::KilledPlayerCredit()
{
    uint16 addkillcount = 1;

    for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
    {
        uint32 questid = GetQuestSlotQuestId(i);
        if (!questid)
            continue;

        Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
        if (!qInfo)
            continue;
        // just if !ingroup || !noraidgroup || raidgroup
        QuestStatusData& q_status = m_QuestStatus[questid];
        if (q_status.Status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->IsAllowedInRaid()))
        {
            for (QuestObjective l_Objective : qInfo->QuestObjectives)
            {
                if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_PLAYER)
                {
                    uint32 currentCounter = GetQuestObjectiveCounter(l_Objective.ID);
                    if (currentCounter < uint32(l_Objective.Amount))
                    {
                        m_questObjectiveStatus[l_Objective.ID] = currentCounter + addkillcount;
                        m_QuestStatusSave[questid] = true;

                        SendQuestUpdateAddPlayer(qInfo, l_Objective, currentCounter, addkillcount);
                    }

                    if (CanCompleteQuest(questid))
                        CompleteQuest(questid);

                    break;
                }
            }
        }
    }
}

void Player::CastedCreatureOrGO(uint32 entry, uint64 guid, uint32 spell_id) ///< entry is unused
{
    QuestObjectiveSatisfy(spell_id, 1, QUEST_OBJECTIVE_TYPE_SPELL, guid);
}

void Player::TalkedToCreature(uint32 entry, uint64 guid)
{
    QuestObjectiveSatisfy(entry, 1, QUEST_OBJECTIVE_TYPE_NPC_INTERACT, guid);
}

void Player::MoneyChanged(uint32 count)
{
    for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
    {
        uint32 questid = GetQuestSlotQuestId(i);
        if (!questid)
            continue;

        Quest const* qInfo = sObjectMgr->GetQuestTemplate(questid);
        if (qInfo && qInfo->GetRewMoney() < 0)
        {
            QuestStatusData& q_status = m_QuestStatus[questid];

            if (q_status.Status == QUEST_STATUS_INCOMPLETE)
            {
                if (int32(count) >= -qInfo->GetRewMoney())
                {
                    if (CanCompleteQuest(questid))
                        CompleteQuest(questid);
                }
            }
            else if (q_status.Status == QUEST_STATUS_COMPLETE)
            {
                if (int32(count) < -qInfo->GetRewMoney())
                    IncompleteQuest(questid);
            }
        }
    }
}

void Player::ReputationChanged(FactionEntry const* factionEntry)
{
    ReputationChangedQuestCheck(factionEntry);
}

void Player::ReputationChanged2(FactionEntry const* factionEntry)<--- The function 'ReputationChanged2' is never used.
{
    ReputationChangedQuestCheck(factionEntry);
}

void Player::ReputationChangedQuestCheck(FactionEntry const* factionEntry)
{
    for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
    {
        uint32 questId = GetQuestSlotQuestId(i);
        if (questId)
            continue;

        Quest const* qInfo = sObjectMgr->GetQuestTemplate(questId);
        if (!qInfo)
            continue;

        if (!qInfo->GetQuestObjectiveCountType(QUEST_OBJECTIVE_TYPE_FACTION_REP2))
            continue;

        QuestStatusData& questStatus = m_QuestStatus[questId];

        for (QuestObjective l_Objective : qInfo->QuestObjectives)
        {
            if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_FACTION_REP2 || l_Objective.Type == QUEST_OBJECTIVE_TYPE_FACTION_REP)
            {
                if (questStatus.Status == QUEST_STATUS_INCOMPLETE)
                {
                    if (GetReputationMgr().GetReputation(factionEntry) >= l_Objective.Amount)
                        if (CanCompleteQuest(questId))
                            CompleteQuest(questId);
                }
                else if (questStatus.Status == QUEST_STATUS_COMPLETE)
                {
                    if (GetReputationMgr().GetReputation(factionEntry) < l_Objective.Amount)
                        IncompleteQuest(questId);
                }
            }
        }
    }
}

void Player::QuestObjectiveSatisfy(uint32 objectId, uint32 amount, uint8 type, uint64 guid)
{
    for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
    {
        uint32 questId = GetQuestSlotQuestId(i);
        if (!questId)
            continue;

        Quest const* quest = sObjectMgr->GetQuestTemplate(questId);
        if (!quest)
            continue;

        QuestStatusData& questStatus = m_QuestStatus[questId];
        if (questStatus.Status != QUEST_STATUS_INCOMPLETE)
            continue;

        if (type)
        {
            if (!quest->GetQuestObjectiveCountType(type))
                continue;
        }

        for (QuestObjective l_Objective : quest->QuestObjectives)
        {
            if (l_Objective.Type == type && (uint32)l_Objective.ObjectID == objectId)
            {
                uint32 currentCounter   = GetQuestObjectiveCounter(l_Objective.ID);
                uint32 requiredCounter  = uint32(l_Objective.Amount);
                uint32 addCounter       = currentCounter + amount > requiredCounter ? requiredCounter : currentCounter +amount;

                m_questObjectiveStatus[l_Objective.ID] = addCounter;
                m_QuestStatusSave[questId] = true;

                SendQuestUpdateAddCredit(quest, l_Objective, guid, currentCounter, amount);

                if (CanCompleteQuest(questId))
                    CompleteQuest(questId);

                break;
            }
        }
    }
}

bool Player::HasQuestForItem(uint32 itemid) const
{
    if (!itemid)
        return false;

    for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
    {
        uint32 questid = GetQuestSlotQuestId(i);
        if (questid == 0)
            continue;

        QuestStatusMap::const_iterator qs_itr = m_QuestStatus.find(questid);
        if (qs_itr == m_QuestStatus.end())
            continue;

        QuestStatusData const& q_status = qs_itr->second;

        if (q_status.Status == QUEST_STATUS_INCOMPLETE)
        {
            Quest const* qinfo = sObjectMgr->GetQuestTemplate(questid);
            if (!qinfo)
                continue;

            // hide quest if player is in raid-group and quest is no raid quest
            if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid())
                if (!InBattleground()) //there are two ways.. we can make every bg-quest a raidquest, or add this code here.. i don't know if this can be exploited by other quests, but i think all other quests depend on a specific area.. but keep this in mind, if something strange happens later
                    continue;

            for (QuestObjective l_QuestObjective : qinfo->QuestObjectives)
            {
                if (itemid == (uint32)l_QuestObjective.ObjectID && GetQuestObjectiveCounter(l_QuestObjective.ID) < uint32(l_QuestObjective.Amount))
                    return true;
            }

            // This part - for ReqSource
            for (uint8 j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
            {
                // examined item is a source item
                if (qinfo->RequiredSourceItemId[j] == itemid)
                {
                    ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(itemid);

                    // 'unique' item
                    if (pProto->MaxCount && int32(GetItemCount(itemid, true)) < pProto->MaxCount)
                        return true;

                    // allows custom amount drop when not 0
                    if (qinfo->RequiredSourceItemCount[j])
                    {
                        if (GetItemCount(itemid, true) < qinfo->RequiredSourceItemCount[j])
                            return true;
                    }
                    else if (GetItemCount(itemid, true) < pProto->GetMaxStackSize())
                        return true;
                }
            }
        }
    }
    return false;
}

bool Player::HasQuest(uint32 p_QuestID) const
{
    for (uint8 l_I = 0; l_I < MAX_QUEST_LOG_SIZE; ++l_I)
    {
        uint32 l_QuestID = GetQuestSlotQuestId(l_I);
        if (l_QuestID == 0)
            continue;

        if (l_QuestID == p_QuestID)
            return true;
    }

    return false;
}

void Player::SendQuestComplete(Quest const* quest)
{
    if (quest)
    {
        WorldPacket data(SMSG_QUEST_UPDATE_COMPLETE, 4);
        data << uint32(quest->GetQuestId());
        GetSession()->SendPacket(&data);
    }
}

void Player::SendQuestReward(Quest const* quest, uint32 XP, Object* questGiver)
{
    uint32 questId = quest->GetQuestId();
    sGameEventMgr->HandleQuestComplete(questId);

    uint32 xp;
    uint32 moneyReward;

    if (getLevel() < sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
    {
        xp = XP;
        moneyReward = quest->GetRewMoney();
    }
    else // At max level, increase gold reward
    {
        xp = 0;
        moneyReward = uint32(quest->GetRewMoney() + int32(quest->GetRewMoneyMaxLevel() * sWorld->getRate(RATE_DROP_MONEY)));
    }

    WorldPacket data(SMSG_QUEST_GIVER_QUEST_COMPLETE, 38);
    data << uint32(questId);
    data << uint32(xp);
    data << uint32(quest->GetRewardSkillId());             ///< Bonus skill id
    data << uint32(quest->GetRewardSkillPoints());         ///< Bonus skill points
    data << uint32(quest->GetBonusTalents());              ///< Bonus talents
    data << uint32(moneyReward);

    data << uint32(0);
    data << uint32(0);
    data << uint32(0);
    data.WriteBit(0);
    data.WriteBit(0);
    data.FlushBits();

    data.WriteBit(1);                                      ///< LaunchGossip
    data.WriteBit(1);                                      ///< UseQuestReward
    data.FlushBits();

    GetSession()->SendPacket(&data);

    if (quest->GetQuestCompleteScript() != 0)
        GetMap()->ScriptsStart(sQuestEndScripts, quest->GetQuestCompleteScript(), questGiver, this);
}

void Player::SendQuestFailed(uint32 questId, InventoryResult reason)
{
    if (questId)
    {
        WorldPacket data(SMSG_QUEST_GIVER_QUEST_FAILED, 4 + 4);
        data << uint32(questId);
        data << uint32(reason);                             // Failed reason (valid reasons: 4, 16, 50, 17, 74, other values show default message)
        GetSession()->SendPacket(&data);
    }
}

void Player::SendQuestTimerFailed(uint32 quest_id)
{
    if (quest_id)
    {
        WorldPacket data(SMSG_QUEST_UPDATE_FAILED_TIMER, 4);
        data << uint32(quest_id);
        GetSession()->SendPacket(&data);
    }
}

/// @TODO
/// according to c9e138d66d6a455a72d3fefbc0e4d5998bc338d6 from TrinityCore
/// the correct struct is
/// data << uint32(Reason);
/// data.WriteBit(SendErrorMessage);
/// data.WriteBits(ReasonText.length(), 9);
/// data.FlushBits();
/// data.WriteString(ReasonText);
void Player::SendCanTakeQuestResponse(uint32 msg) const
{
    WorldPacket data(SMSG_QUEST_GIVER_INVALID_QUEST, 4 + 2);
    data << uint32(msg);
    data.WriteBits(0, 9);       ///< Reason text
    data.FlushBits();
    GetSession()->SendPacket(&data);
}

void Player::SendQuestConfirmAccept(const Quest* quest, Player* pReceiver)
{
    if (pReceiver)
    {
        std::string strTitle = quest->GetTitle();

        int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
        if (loc_idx >= 0)
            if (const QuestLocale* pLocale = sObjectMgr->GetQuestLocale(quest->GetQuestId()))
                ObjectMgr::GetLocaleString(pLocale->Title, loc_idx, strTitle);

        WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, 200);
        data << uint32(quest->GetQuestId());
        data.appendPackGUID(GetGUID());
        data.WriteBits(strTitle.size(), 10);
        data.FlushBits();
        data.WriteString(strTitle);
        pReceiver->GetSession()->SendPacket(&data);
    }
}

void Player::SendPushToPartyResponse(Player* player, uint32 msg)
{
    if (player)
    {
        WorldPacket data(SMSG_QUEST_PUSH_RESULT, 16 + 2 + 1);

        data.appendPackGUID(player->GetGUID());
        data << uint8(msg);

        GetSession()->SendPacket(&data);
    }
}

void Player::SendQuestUpdateAddCredit(Quest const* p_Quest, const QuestObjective & p_Objective, uint64 p_ObjGUID, uint16 p_OldCount, uint16 p_AddCount)
{
    ASSERT(p_OldCount + p_AddCount < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");

    uint16 log_slot = FindQuestSlot(p_Quest->GetQuestId());

    switch (p_Objective.Type)
    {
        case QUEST_OBJECTIVE_TYPE_CRITERIA_TREE:
        {
            WorldPacket data(SMSG_QUEST_UPDATE_ADD_CREDIT_SIMPLE, (4 * 4 + 8));
            data << uint32(p_Quest->GetQuestId());
            data << uint32(p_Objective.ObjectID);
            data << uint8(p_Objective.Type);

            GetSession()->SendPacket(&data);

            if (log_slot < MAX_QUEST_LOG_SIZE)
                SetQuestSlotState(log_slot, QUEST_STATE_OBJ_0_COMPLETE << p_Objective.Index);

            break;
        }

        case QUEST_OBJECTIVE_TYPE_NPC:
        case QUEST_OBJECTIVE_TYPE_ITEM:
        case QUEST_OBJECTIVE_TYPE_GO:
        case QUEST_OBJECTIVE_TYPE_NPC_INTERACT:
        case QUEST_OBJECTIVE_TYPE_CURRENCY:
        case QUEST_OBJECTIVE_TYPE_SPELL:
        case QUEST_OBJECTIVE_TYPE_FACTION_REP:
        case QUEST_OBJECTIVE_TYPE_FACTION_REP2:
        case QUEST_OBJECTIVE_TYPE_MONEY:
        case QUEST_OBJECTIVE_TYPE_PLAYER:
        case QUEST_OBJECTIVE_TYPE_AREATRIGGER:
        case QUEST_OBJECTIVE_TYPE_PET_BATTLE_TAMER:
        case QUEST_OBJECTIVE_TYPE_PET_BATTLE_ELITE:
        case QUEST_OBJECTIVE_TYPE_PET_BATTLE_PVP:
        case QUEST_OBJECTIVE_TYPE_PET_BATTLE_UNK2:
        default:
        {
            WorldPacket data(SMSG_QUEST_UPDATE_ADD_CREDIT, (4 * 4 + 8));
            data.appendPackGUID(p_ObjGUID);
            data << uint32(p_Quest->GetQuestId());
            data << uint32(p_Objective.ObjectID);
            data << uint16(p_OldCount + p_AddCount);
            data << uint16(p_Objective.Amount);
            data << uint8(p_Objective.Type);

            GetSession()->SendPacket(&data);

            if (log_slot < MAX_QUEST_LOG_SIZE)
                SetQuestSlotCounter(log_slot, p_Objective.Index, GetQuestSlotCounter(log_slot, p_Objective.Index) + p_AddCount);

            break;
        }
    }
}

void Player::SendQuestUpdateAddPlayer(Quest const* p_Quest, const QuestObjective & p_Objective, uint16 p_OldCount, uint16 p_AddCount)
{
    ASSERT(p_OldCount + p_AddCount < 65536 && "player count store in 16 bits");

    WorldPacket data(SMSG_QUEST_UPDATE_ADD_PVP_CREDIT, (2*4) + 1);
    data << uint32(p_Quest->GetQuestId());
    data << uint16(p_OldCount + p_AddCount);
    GetSession()->SendPacket(&data);

    uint16 log_slot = FindQuestSlot(p_Quest->GetQuestId());

    if (log_slot < MAX_QUEST_LOG_SIZE)
        SetQuestSlotCounter(log_slot, p_Objective.Index, GetQuestSlotCounter(log_slot, p_Objective.Index) + p_AddCount);
}

/*********************************************************/
/***                   LOAD SYSTEM                     ***/
/*********************************************************/
void Player::Initialize(uint32 guid)
{
    Object::_Create(guid, 0, HIGHGUID_PLAYER);
}

void Player::_LoadDeclinedNames(PreparedQueryResult result)
{
    if (!result)
        return;

    delete m_declinedname;
    m_declinedname = new DeclinedName;
    for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
        m_declinedname->name[i] = (*result)[i].GetString();
}

void Player::_LoadEquipmentSets(PreparedQueryResult result)
{
    // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS,   "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
    if (!result)
        return;

    uint32 count = 0;
    do
    {
        Field* fields = result->Fetch();
        EquipmentSet eqSet;

        eqSet.Guid      = fields[0].GetUInt64();
        uint8 index    = fields[1].GetUInt8();
        eqSet.Name      = fields[2].GetString();
        eqSet.IconName  = fields[3].GetString();
        eqSet.IgnoreMask = fields[4].GetUInt32();
        eqSet.state     = EQUIPMENT_SET_UNCHANGED;

        for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
            eqSet.Items[i] = fields[5+i].GetUInt32();

        m_EquipmentSets[index] = eqSet;

        ++count;

        if (count >= MAX_EQUIPMENT_SET_INDEX)                // client limit
            break;
    }
    while (result->NextRow());
}

void Player::_LoadArenaData(PreparedQueryResult result)
{
    if (!result)
        return;

    Field* fields = result->Fetch();
    //        0        1                  2                    3                  4           5          6              7             8            9        10                 11                   12                 13          14         15             16            17           18       19                 20                   21                 22          23         24             25            26
    // SELECT rating0, bestRatingOfWeek0, bestRatingOfSeason0, matchMakerRating0, weekGames0, weekWins0, prevWeekWins0, seasonGames0, seasonWins0, rating1, bestRatingOfWeek1, bestRatingOfSeason1, matchMakerRating1, weekGames1, weekWins1, prevWeekWins1, seasonGames1, seasonWins1, rating2, bestRatingOfWeek2, bestRatingOfSeason2, matchMakerRating2, weekGames2, weekWins2, prevWeekWins2, seasonGames2, seasonWins2 FROM character_arena_data WHERE guid = ?

    uint8 j = 0;
    for (uint8 i = 0; i < MAX_PVP_SLOT; ++i)
    {
        m_ArenaPersonalRating[i] = fields[j++].GetUInt32();
        m_BestRatingOfWeek[i] = fields[j++].GetUInt32();
        m_BestRatingOfSeason[i] = fields[j++].GetUInt32();
        m_ArenaMatchMakerRating[i] = fields[j++].GetInt32();
        m_WeekGames[i] = fields[j++].GetUInt32();
        m_WeekWins[i] = fields[j++].GetUInt32();
        m_PrevWeekWins[i] = fields[j++].GetUInt32();
        m_PrevWeekGames[i] = fields[j++].GetUInt32();
        m_SeasonGames[i] = fields[j++].GetUInt32();
        m_SeasonWins[i] = fields[j++].GetUInt32();
    }
}

void Player::_LoadBGData(PreparedQueryResult result)
{
    if (!result)
        return;

    Field* fields = result->Fetch();
    // Expecting only one row
    //        0           1     2      3      4      5      6          7          8        9            10
    // SELECT instanceId, team, joinX, joinY, joinZ, joinO, joinMapId, taxiStart, taxiEnd, mountSpell, lastActiveSpec FROM character_battleground_data WHERE guid = ?

    m_bgData.bgInstanceID = fields[0].GetUInt32();
    m_bgData.bgTeam       = fields[1].GetUInt16();
    m_bgData.joinPos      = WorldLocation(fields[6].GetUInt16(),    // Map
                                          fields[2].GetFloat(),     // X
                                          fields[3].GetFloat(),     // Y
                                          fields[4].GetFloat(),     // Z
                                          fields[5].GetFloat());    // Orientation
    m_bgData.taxiPath[0]  = fields[7].GetUInt32();
    m_bgData.taxiPath[1]  = fields[8].GetUInt32();
    m_bgData.mountSpell   = fields[9].GetUInt32();
    m_bgData.m_LastActiveSpec = fields[10].GetUInt16();
}

bool Player::LoadPositionFromDB(uint32& mapid, float& x, float& y, float& z, float& o, bool& in_flight, uint64 guid)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_POSITION);
    stmt->setUInt32(0, GUID_LOPART(guid));
    PreparedQueryResult result = CharacterDatabase.Query(stmt);

    if (!result)
        return false;

    Field* fields = result->Fetch();

    x = fields[0].GetFloat();
    y = fields[1].GetFloat();
    z = fields[2].GetFloat();
    o = fields[3].GetFloat();
    mapid = fields[4].GetUInt16();
    in_flight = !fields[5].GetString().empty();

    return true;
}

void Player::SetHomebind(WorldLocation const& loc, uint32 area_id)
{
    m_homebindMapId  = loc.GetMapId();
    m_homebindAreaId = area_id;
    m_homebindX      = loc.GetPositionX();
    m_homebindY      = loc.GetPositionY();
    m_homebindZ      = loc.GetPositionZ();

    // update sql homebind
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_PLAYER_HOMEBIND);
    stmt->setUInt16(0, m_homebindMapId);
    stmt->setUInt16(1, m_homebindAreaId);
    stmt->setFloat (2, m_homebindX);
    stmt->setFloat (3, m_homebindY);
    stmt->setFloat (4, m_homebindZ);
    stmt->setUInt32(5, GetGUIDLow());
    CharacterDatabase.Execute(stmt);
}

uint32 Player::GetUInt32ValueFromArray(Tokenizer const& data, uint16 index)
{
    if (index >= data.size())
        return 0;

    return (uint32)atoi(data[index]);
}

uint64 Player::GetUInt64ValueFromArray(Tokenizer const& p_Datas, uint16 p_Index)
{
    if (p_Index >= p_Datas.size())
        return 0;

    return (uint64)strtoull(p_Datas[p_Index], nullptr, 10);
}

float Player::GetFloatValueFromArray(Tokenizer const& data, uint16 index)<--- The function 'GetFloatValueFromArray' is never used.
{
    float result;
    uint32 temp = Player::GetUInt32ValueFromArray(data, index);
    memcpy(&result, &temp, sizeof(result));

    return result;
}

bool Player::LoadFromDB(uint32 guid, SQLQueryHolder* holder, SQLQueryHolder* p_LoginDBQueryHolder)
{
    /// 0             1               2               3                  4                         5                         6                7                  8                    9
    /// guid,         account,        name,           race,              class,                    gender,                   level,           xp,                money,               playerBytes,
    /// 10            11              12              13                 14                        15                        16               17                 18                   19
    /// playerBytes2, playerFlags,    position_x,     position_y,        position_z,               map,                      orientation,     taximask,          cinematic,           totaltime,
    /// 20            21              22              23                 24                        25                        26               27                 28                   29
    /// leveltime,    rest_bonus,     logout_time,    is_logout_resting, resettalents_cost,        resettalents_time,        talentTree,      trans_x,           trans_y,             trans_z,
    /// 30            31              32              33                 34                        35                        36               37                 38                   39
    /// trans_o,      transguid,      extra_flags,    stable_slots,      at_login,                 zone,                     online,          death_expire_time, taxi_path,           DungeonDifficulty,
    /// 40            41              42              43                 44                        45                        46               47                 48                   49
    /// totalKills,   todayKills,     yesterdayKills, chosenTitle,       watchedFaction,           drunk,                    health,          power1,            power2,              power3,
    /// 50            51              52      53              54                 55                        56                        57               58                 59                   60
    /// power4,       power5,         power6, instance_id,    speccount,         activespec,               specialization1,          specialization2, exploredZones,     equipmentCache,      knownTitles,
    /// 61            62              63              64                 65                        66                        67               68                 69                   70             71
    /// actionBars,   currentpetslot, petslotused,    grantableLevels,   resetspecialization_cost, resetspecialization_time, playerFlagsEx,   RaidDifficulty,    LegacyRaidDifficuly, lastbattlepet, xprate

    uint32 l_StartTime = getMSTime();
    std::vector<uint32> l_Times;

    PreparedQueryResult result = holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADFROM);
    if (!result)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player (GUID: %u) not found in table `characters`, can't load. ", guid);
        return false;
    }

    Field* fields = result->Fetch();

    m_atLoginFlags = fields[34].GetUInt16();

    if (m_atLoginFlags & AT_LOGIN_LOCKED_FOR_TRANSFER)
        return false;

    uint32 dbAccountId = fields[1].GetUInt32();

    // check if the character's account in the db and the logged in account match.
    // player should be able to load/delete character only with correct account!
    if (dbAccountId != GetSession()->GetAccountId())
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player (GUID: %u) loading from wrong account (is: %u, should be: %u)", guid, GetSession()->GetAccountId(), dbAccountId);
        return false;
    }

    if (holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADBANNED))
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player (GUID: %u) is banned, can't load.", guid);
        return false;
    }

    Object::_Create(guid, 0, HIGHGUID_PLAYER);

    if (m_atLoginFlags & AT_LOGIN_CHANGE_ITEM_FACTION)
    {
        uint8 l_CurrentRace = fields[3].GetUInt8();

        BattlegroundTeamId l_Team = BG_TEAM_ALLIANCE;
        switch (l_CurrentRace)
        {
            case RACE_ORC:
            case RACE_GOBLIN:
            case RACE_TAUREN:
            case RACE_UNDEAD_PLAYER:
            case RACE_TROLL:
            case RACE_BLOODELF:
            case RACE_PANDAREN_HORDE:
                l_Team = BG_TEAM_HORDE;
                break;
            default:
                break;
        }

        /// Item conversion
        SQLTransaction l_Transaction = CharacterDatabase.BeginTransaction();
        for (std::map<uint32, uint32>::const_iterator l_Iterator = sObjectMgr->FactionChange_Items.begin(); l_Iterator != sObjectMgr->FactionChange_Items.end(); ++l_Iterator)
        {
            uint32 l_ItemAlliance = l_Iterator->first;
            uint32 l_ItemHorde = l_Iterator->second;

            PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INVENTORY_FACTION_CHANGE);
            l_Statement->setUInt32(0, (l_Team == BG_TEAM_ALLIANCE ? l_ItemAlliance : l_ItemHorde));
            l_Statement->setUInt32(1, (l_Team == BG_TEAM_ALLIANCE ? l_ItemHorde : l_ItemAlliance));
            l_Statement->setUInt32(2, guid);
            l_Transaction->Append(l_Statement);
        }

        CharacterDatabase.DirectCommitTransaction(l_Transaction);

        RemoveAtLoginFlag(AT_LOGIN_CHANGE_ITEM_FACTION, true);
        return false;
    }

    m_name = fields[2].GetString();

    // check name limitations
    if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
        (AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()) && sObjectMgr->IsReservedName(m_name)))
    {
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ADD_AT_LOGIN_FLAG);

        stmt->setUInt16(0, uint16(AT_LOGIN_RENAME));
        stmt->setUInt32(1, guid);

        CharacterDatabase.Execute(stmt);

        return false;
    }

    l_Times.push_back(getMSTime() - l_StartTime);

    // overwrite possible wrong/corrupted guid
    SetGuidValue(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));

    uint8 Gender = fields[5].GetUInt8();
    if (!IsValidGender(Gender))
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player (GUID: %u) has wrong gender (%hhu), can't be loaded.", guid, Gender);
        return false;
    }

    // overwrite some data fields
    uint32 bytes0 = 0;
    bytes0 |= fields[3].GetUInt8();                         // race
    bytes0 |= fields[4].GetUInt8() << 8;                    // class
    bytes0 |= Gender << 24;                                 // gender
    SetUInt32Value(UNIT_FIELD_SEX, bytes0);

    SetUInt32Value(UNIT_FIELD_LEVEL, fields[6].GetUInt8());
    SetUInt32Value(PLAYER_FIELD_XP, fields[7].GetUInt32());

    _LoadIntoDataField(fields[58].GetCString(), PLAYER_FIELD_EXPLORED_ZONES, PLAYER_EXPLORED_ZONES_SIZE, false);
    _LoadIntoDataField(fields[60].GetCString(), PLAYER_FIELD_KNOWN_TITLES, KNOWN_TITLES_SIZE, true);

    SetFloatValue(UNIT_FIELD_BOUNDING_RADIUS, DEFAULT_WORLD_OBJECT_SIZE);
    SetFloatValue(UNIT_FIELD_COMBAT_REACH, 1.5f);
    SetFloatValue(UNIT_FIELD_HOVER_HEIGHT, 1.0f);

    // load achievements before anything else to prevent multiple gains for the same achievement/criteria on every loading (as loading does call UpdateAchievementCriteria)
    m_achievementMgr.LoadFromDB(this, NULL, holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS),
                                holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS),
                                holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADACCOUNTACHIEVEMENTS),
                                holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADACCOUNTCRITERIAPROGRESS));

    uint64 money = fields[8].GetUInt64();
    if (money > MAX_MONEY_AMOUNT)
        money = MAX_MONEY_AMOUNT;
    SetMoney(money);

    l_Times.push_back(getMSTime() - l_StartTime);

    SetUInt32Value(PLAYER_FIELD_HAIR_COLOR_ID, fields[9].GetUInt32());
    SetUInt32Value(PLAYER_FIELD_REST_STATE, fields[10].GetUInt32());
    SetByteValue(PLAYER_FIELD_ARENA_FACTION, PLAYER_BYTES_3_OFFSET_GENDER, fields[5].GetUInt8());
    SetByteValue(PLAYER_FIELD_ARENA_FACTION, PLAYER_BYTES_3_OFFSET_INEBRIATION, fields[45].GetUInt8());
    SetUInt32Value(PLAYER_FIELD_PLAYER_FLAGS, fields[11].GetUInt32());
    SetUInt32Value(PLAYER_FIELD_PLAYER_FLAGS_EX, fields[67].GetUInt32());
    SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[44].GetUInt32());

    SetGuidValue(PLAYER_FIELD_WOW_ACCOUNT, GetSession()->GetWoWAccountGUID());

    // set which actionbars the client has active - DO NOT REMOVE EVER AGAIN (can be changed though, if it does change fieldwise)
    SetByteValue(PLAYER_FIELD_LIFETIME_MAX_RANK, PLAYER_FIELD_BYTES_OFFSET_ACTION_BAR_TOGGLES, fields[61].GetUInt8());

    m_currentPetSlot = (PetSlot)fields[62].GetUInt8();

    InitDisplayIds();

    // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
    for (uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
    {
        SetGuidValue(PLAYER_FIELD_INV_SLOTS + (slot * 4), 0);
        SetVisibleItemSlot(slot, NULL);

        delete m_items[slot];
        m_items[slot] = NULL;
    }

    sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Load Basic value of player %s is: ", m_name.c_str());
    outDebugValues();

    //Need to call it to initialize m_team (m_team can be calculated from race)
    //Other way is to saves m_team into characters table.
    setFactionForRace(getRace());

    // load home bind and check in same time class/race pair, it used later for restore broken positions
    if (!_LoadHomeBind(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
        return false;

    InitPrimaryProfessions();                               // to max set before any spell loaded

    l_Times.push_back(getMSTime() - l_StartTime);

    // init saved position, and fix it later if problematic
    uint32 transGUID = uint32(fields[31].GetUInt32());

    Relocate(fields[12].GetFloat(), fields[13].GetFloat(), fields[14].GetFloat(), fields[16].GetFloat());

    uint32 mapId = fields[15].GetUInt16();
    uint32 instanceId = fields[53].GetUInt32();

    SetDungeonDifficultyID(CheckLoadedDungeonDifficultyID(Difficulty(fields[39].GetUInt8())));
    SetRaidDifficultyID(CheckLoadedRaidDifficultyID(Difficulty(fields[68].GetUInt8())));
    SetLegacyRaidDifficultyID(CheckLoadedLegacyRaidDifficultyID(Difficulty(fields[69].GetUInt8())));

    std::string taxi_nodes = fields[38].GetString();
    l_Times.push_back(getMSTime() - l_StartTime);

#define RelocateToHomebind(){ mapId = m_homebindMapId; instanceId = 0; Relocate(m_homebindX, m_homebindY, m_homebindZ); }

    _LoadHeirloomCollection(p_LoginDBQueryHolder->GetPreparedResult(PLAYER_LOGINDB_HEIRLOOM_COLLECTION));
    _LoadToyBox(p_LoginDBQueryHolder->GetPreparedResult(PLAYER_LOGINDB_TOYS));
    _LoadBossLooted(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_BOSS_LOOTED));
    _LoadWorldStates(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_WORLD_STATES));

    _LoadGroup(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADGROUP));

    _LoadArenaData(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADARENADATA));
    _LoadCurrency(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADCURRENCY));
    SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS, fields[40].GetUInt32());
    SetUInt16Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 0, fields[41].GetUInt16());
    SetUInt16Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 1, fields[42].GetUInt16());

    _LoadBoundInstances(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
    _LoadInstanceTimeRestrictions(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADINSTANCELOCKTIMES));
    _LoadBGData(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
    _LoadCUFProfiles(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_CUF_PROFILES));
    l_Times.push_back(getMSTime() - l_StartTime);

    GetSession()->SetPlayer(this);
    MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);

    bool mustResurrectFromUnlock = false;

    if (m_atLoginFlags & AT_LOGIN_UNLOCK)
    {
        bool BGdesert = false;
        bool DungeonDesert = false;
        bool MalDeRez = false;

        RemoveAtLoginFlag(AT_LOGIN_UNLOCK, true);
        if (HasAura(26013)) // deserteur
            BGdesert = true;
        if (HasAura(71041)) // deserteur de donjon
            DungeonDesert = true;
        if (HasAura(15007))
            MalDeRez = true;

        RemoveAllAuras();
        RemoveFromGroup();
        CleanupAfterTaxiFlight();

        if (BGdesert)
            AddAura(26013, this);
        if (DungeonDesert)
            AddAura(71041, this);
        /*if (MalDeRez)
            AddAura(15007, this);*/

        mustResurrectFromUnlock = HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GHOST);
        RelocateToHomebind();
    }
    else if (!mapEntry || !IsPositionValid())
    {
        RemoveAtLoginFlag(AT_LOGIN_UNLOCK, true);
        sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) have invalid coordinates (MapId: %u X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid, mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
        RelocateToHomebind();
    }
    // currently we do not support transport in bg
    else if (transGUID)
    {
        m_movementInfo.t_guid = MAKE_NEW_GUID(transGUID, 0, HIGHGUID_MO_TRANSPORT);
        m_movementInfo.t_pos.Relocate(fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat(), fields[30].GetFloat());

        if (!JadeCore::IsValidMapCoord(
            GetPositionX()+m_movementInfo.t_pos.m_positionX, GetPositionY()+m_movementInfo.t_pos.m_positionY,
            GetPositionZ()+m_movementInfo.t_pos.m_positionZ, GetOrientation()+m_movementInfo.t_pos.GetOrientation()) ||
            // transport size limited
            m_movementInfo.t_pos.m_positionX > 250 || m_movementInfo.t_pos.m_positionY > 250 || m_movementInfo.t_pos.m_positionZ > 250)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to bind location.",
                guid, GetPositionX()+m_movementInfo.t_pos.m_positionX, GetPositionY()+m_movementInfo.t_pos.m_positionY,
                GetPositionZ()+m_movementInfo.t_pos.m_positionZ, GetOrientation()+m_movementInfo.t_pos.GetOrientation());

            RelocateToHomebind();
        }
        else
        {
            if (GameObject* go = HashMapHolder<GameObject>::Find(m_movementInfo.t_guid))
                m_transport = go->ToTransport();

            if (m_transport)
            {
                m_transport->AddPassenger(this);
                mapId = m_transport->GetMapId();
            }
            else
            {
                sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) have problems with transport guid (%u). Teleport to bind location.",
                    guid, transGUID);

                RelocateToHomebind();
            }
        }
    }
    // currently we do not support taxi in instance
    else if (!taxi_nodes.empty())
    {
        instanceId = 0;

        // Not finish taxi flight path
        if (m_bgData.HasTaxiPath())
        {
            for (int i = 0; i < 2; ++i)
                m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
        }
        else if (!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes, GetTeam()))
        {
            // problems with taxi path loading
            TaxiNodesEntry const* nodeEntry = NULL;
            if (uint32 node_id = m_taxi.GetTaxiSource())
                nodeEntry = sTaxiNodesStore.LookupEntry(node_id);

            if (!nodeEntry)                                      // don't know taxi start node, to homebind
            {
                sLog->outError(LOG_FILTER_PLAYER, "Character %u have wrong data in taxi destination list, teleport to homebind.", GetGUIDLow());
                RelocateToHomebind();
            }
            else                                                // have start node, to it
            {
                sLog->outError(LOG_FILTER_PLAYER, "Character %u have too short taxi destination list, teleport to original node.", GetGUIDLow());
                mapId = nodeEntry->MapID;
                Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z, 0.0f);
            }
            m_taxi.ClearTaxiDestinations();
        }

        if (uint32 node_id = m_taxi.GetTaxiSource())
        {
            // save source node as recall coord to prevent recall and fall from sky
            TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
            if (nodeEntry && nodeEntry->MapID == GetMapId())
            {
                ASSERT(nodeEntry);                                  // checked in m_taxi.LoadTaxiDestinationsFromString
                mapId = nodeEntry->MapID;
                Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z, 0.0f);
            }

            // flight will started later
        }
    }

    // Map could be changed before
    mapEntry = sMapStore.LookupEntry(mapId);
    // client without expansion support
    if (mapEntry)
    {
        if (GetSession()->Expansion() < mapEntry->Expansion())
        {
            sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player %s using client without required expansion tried login at non accessible map %u", GetName(), mapId);
            RelocateToHomebind();
        }

        // fix crash (because of if (Map* map = _FindMap(instanceId)) in MapInstanced::CreateInstance)
        if (instanceId)
            if (InstanceSave* save = GetInstanceSave(mapId))
                if (save->GetInstanceId() != instanceId)
                    instanceId = 0;
    }

    l_Times.push_back(getMSTime() - l_StartTime);

    /// Player was saved in BG or arena.
    if (mapEntry && mapEntry->IsBattlegroundOrArena())
    {
        Battleground* currentBg = NULL;
        if (m_bgData.bgInstanceID)                                                //saved in Battleground
            currentBg = sBattlegroundMgr->GetBattleground(m_bgData.bgInstanceID, MS::Battlegrounds::Maps::FindAssociatedType(mapEntry->MapID));

        bool player_at_bg = currentBg && currentBg->IsPlayerInBattleground(GetGUID());

        if (player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
        {
            MS::Battlegrounds::BattlegroundType::Type bgQueueTypeId = MS::Battlegrounds::GetTypeFromId(currentBg->GetTypeID(), currentBg->GetArenaType(), currentBg->IsSkirmish());
            AddBattlegroundQueueId(bgQueueTypeId);

            m_bgData.bgTypeID = currentBg->GetTypeID();

            //join player to battleground group
            currentBg->EventPlayerLoggedIn(this);
            currentBg->AddOrSetPlayerToCorrectBgGroup(this, m_bgData.bgTeam);

            SetInviteForBattlegroundQueueType(bgQueueTypeId, currentBg->GetInstanceID());

            /// We give the deserter aura by default when we leave a battleground
            /// so if we succeed at re-entering the battleground, we remove the aura.
            if (HasAura(MS::Battlegrounds::Spells::DeserterBuff))
                RemoveAura(MS::Battlegrounds::Spells::DeserterBuff);
        }
        // Bg was not found - go to Entry Point
        else
        {
            /// Leave bg.
            if (player_at_bg)
                currentBg->RemovePlayerAtLeave(GetGUID(), false, true);

            /// Do not look for instance if bg not found.
            const WorldLocation& _loc = GetBattlegroundEntryPoint();
            mapId = _loc.GetMapId(); instanceId = 0;

            /// Db field type is type int16, so it can never be MAPID_INVALID.
            /// if (mapId == MAPID_INVALID) -- code kept for reference
            if (int16(mapId) == int16(-1)) // Battleground Entry Point not found (???)
            {
                sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) was in BG in database, but BG was not found, and entry point was invalid! Teleport to default race/class locations.", guid);
                RelocateToHomebind();
            }
            else
                Relocate(&_loc);

            /// We are not in BG anymore.
            m_bgData.bgInstanceID = 0;
        }
    }

    // NOW player must have valid map
    // load the player's map here if it's not already loaded
    Map* map = sMapMgr->CreateMap(mapId, this);

    if (!map)
    {
        instanceId = 0;
        AreaTriggerStruct const* at = sObjectMgr->GetGoBackTrigger(mapId);
        if (at)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) is teleported to gobacktrigger (Map: %u X: %f Y: %f Z: %f O: %f).", guid, mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
            Relocate(at->target_X, at->target_Y, at->target_Z, GetOrientation());
            mapId = at->target_mapId;
        }
        else
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) is teleported to home (Map: %u X: %f Y: %f Z: %f O: %f).", guid, mapId, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
            RelocateToHomebind();
        }

        map = sMapMgr->CreateMap(mapId, this);
        if (!map)
        {
            PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
            mapId = info->mapId;
            Relocate(info->positionX, info->positionY, info->positionZ, 0.0f);
            sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.", guid, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
            map = sMapMgr->CreateMap(mapId, this);
            if (!map)
            {
                sLog->outError(LOG_FILTER_PLAYER, "Player (guidlow %d) has invalid default map coordinates (X: %f Y: %f Z: %f O: %f). or instance couldn't be created", guid, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
                return false;
            }
        }
    }

    l_Times.push_back(getMSTime() - l_StartTime);

    // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
    if (instanceId && !sInstanceSaveMgr->GetInstanceSave(instanceId) && !map->IsBattlegroundOrArena())
    {
        AreaTriggerStruct const* at = sObjectMgr->GetMapEntranceTrigger(mapId);
        if (at)
            Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
        else
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), mapId);
            RelocateToHomebind();
        }
    }

    SetMap(map);

    // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
    // this must help in case next save after mass player load after server startup
    m_nextSave = urand(m_nextSave/2, m_nextSave*3/2);

    SaveRecallPosition();

    time_t now = time(NULL);
    time_t logoutTime = time_t(fields[22].GetUInt32());

    // since last logout (in seconds)
    uint32 time_diff = uint32(now - logoutTime); //uint64 is excessive for a time_diff in seconds.. uint32 allows for 136~ year difference.

    // set value, including drunk invisibility detection
    // calculate sobering. after 15 minutes logged out, the player will be sober again
    uint8 newDrunkValue = 0;
    if (time_diff < uint32(GetDrunkValue()) * 9)
        newDrunkValue = GetDrunkValue() - time_diff / 9;

    SetDrunkValue(newDrunkValue);

    m_cinematic = fields[18].GetUInt8();
    m_Played_time[PLAYED_TIME_TOTAL]= fields[19].GetUInt32();
    m_Played_time[PLAYED_TIME_LEVEL]= fields[20].GetUInt32();

    SetTalentResetCost(fields[24].GetUInt32());
    SetTalentResetTime(time_t(fields[25].GetUInt32()));

    SetSpecializationResetCost(fields[65].GetUInt32());
    SetSpecializationResetTime(time_t(fields[66].GetUInt32()));

    m_taxi.LoadTaxiMask(fields[17].GetCString());            // must be before InitTaxiNodesForLevel

    uint32 extraflags = fields[32].GetUInt16();

    l_Times.push_back(getMSTime() - l_StartTime);

    m_stableSlots = fields[33].GetUInt8();
    if (m_stableSlots > MAX_PET_STABLES)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player can have not more %u stable slots, but have in DB %u", MAX_PET_STABLES, uint32(m_stableSlots));
        m_stableSlots = MAX_PET_STABLES;
    }

    // Honor system
    // Update Honor kills data
    m_lastHonorUpdateTime = logoutTime;
    UpdateHonorFields();

    m_deathExpireTime = time_t(fields[37].GetUInt32());
    if (m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
        m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;

    m_LastSummonedBattlePet = fields[70].GetUInt32();
    m_PersonnalXpRate = fields[71].GetFloat();

    // clear channel spell data (if saved at channel spell casting)
    SetGuidValue(UNIT_FIELD_CHANNEL_OBJECT, 0);
    SetUInt32Value(UNIT_FIELD_CHANNEL_SPELL, 0);
    SetUInt32Value(UNIT_FIELD_CHANNEL_SPELL_XSPELL_VISUAL, 0);

    // clear charm/summon related fields
    SetOwnerGUID(0);
    SetGuidValue(UNIT_FIELD_CHARMED_BY, 0);
    SetGuidValue(UNIT_FIELD_CHARM, 0);
    SetGuidValue(UNIT_FIELD_SUMMON, 0);
    SetGuidValue(PLAYER_FIELD_FARSIGHT_OBJECT, 0);
    SetCreatorGUID(0);

    RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVEMENT);

    // reset some aura modifiers before aura apply
    SetUInt32Value(PLAYER_FIELD_TRACK_CREATURE_MASK, 0);
    SetUInt32Value(PLAYER_FIELD_TRACK_RESOURCE_MASK, 0);

    // make sure the unit is considered out of combat for proper loading
    ClearInCombat();

    // make sure the unit is considered not in duel for proper loading
    SetGuidValue(PLAYER_FIELD_DUEL_ARBITER, 0);
    SetUInt32Value(PLAYER_FIELD_DUEL_TEAM, 0);

    l_Times.push_back(getMSTime() - l_StartTime);

    // reset stats before loading any modifiers
    InitStatsForLevel();
    InitGlyphsForLevel();
    InitTaxiNodesForLevel();
    InitRunes();

    l_Times.push_back(getMSTime() - l_StartTime);

    // rest bonus can only be calculated after InitStatsForLevel()
    m_rest_bonus = fields[21].GetFloat();

    if (time_diff > 0)
    {
        //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
        float bubble0 = 0.031f;
        //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
        float bubble1 = 0.125f;
        float bubble = fields[23].GetUInt8() > 0
            ? bubble1*sWorld->getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
            : bubble0*sWorld->getRate(RATE_REST_OFFLINE_IN_WILDERNESS);

        SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_FIELD_NEXT_LEVEL_XP)/72000)*bubble);
    }

    // load skills after InitStatsForLevel because it triggering aura apply also
    _LoadSkills(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
    m_archaeologyMgr.LoadArchaeology(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_ARCHAEOLOGY),
                                     holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_ARCHAEOLOGY_PROJECTS),
                                     holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_ARCHAEOLOGY_SITES));

    // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()

    //mails are loaded only when needed ;-) - when player in game click on mailbox.
    _LoadMail(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADMAIL));
    _LoadMailedItems(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADMAIL_ITEMS));

    SetSpecsCount(fields[54].GetUInt8());
    SetActiveSpec(fields[55].GetUInt8());

    SetSpecializationId(0, fields[56].GetUInt32(), true);
    SetSpecializationId(1, fields[57].GetUInt32(), true);

    SetFreeTalentPoints(CalculateTalentsPoints());

    l_Times.push_back(getMSTime() - l_StartTime);

    // sanity check
    if (GetSpecsCount() > MAX_TALENT_SPECS || GetActiveSpec() > MAX_TALENT_SPEC || GetSpecsCount() < MIN_TALENT_SPECS)
    {
        SetActiveSpec(0);
        sLog->outError(LOG_FILTER_PLAYER, "Player %s(GUID: %u) has SpecCount = %u and ActiveSpec = %u.", GetName(), GetGUIDLow(), GetSpecsCount(), GetActiveSpec());
    }

    _LoadGlyphs(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADGLYPHS));
    l_Times.push_back(getMSTime() - l_StartTime);

    _LoadGlyphAuras();
    l_Times.push_back(getMSTime() - l_StartTime);

    _LoadTalents(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADTALENTS));
    l_Times.push_back(getMSTime() - l_StartTime);

    _LoadSpells(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_CHAR_LOADSPELLS));

    l_Times.push_back(getMSTime() - l_StartTime);

    uint32 l_AllowedGroupRealmMask = sWorld->getIntConfig(CONFIG_ACCOUNT_BIND_ALLOWED_GROUP_MASK);

    // Load of account spell, we must load it like that because it's stored in realmd database
    // With actual implementation, we can use QueryHolder only with single database
    if (PreparedQueryResult accountResult = p_LoginDBQueryHolder->GetPreparedResult(PLAYER_LOGINGB_SPELL))
    {
        do
        {
            uint32 l_GroupRealmMask = (*accountResult)[4].GetUInt32();
            if ((l_GroupRealmMask & l_AllowedGroupRealmMask) == 0)
                continue;

            uint32 l_SpellID = (*accountResult)[0].GetUInt32();
            for (uint32 l_I = 0; l_I < sBattlePetSpeciesStore.GetNumRows(); l_I++)
            {
                BattlePetSpeciesEntry const* speciesInfo = sBattlePetSpeciesStore.LookupEntry(l_I);

                if (speciesInfo && speciesInfo->spellId == l_SpellID)
                {
                    m_OldPetBattleSpellToMerge.push_back(std::make_pair(l_SpellID, speciesInfo->id));
                    break;
                }
            }

            addSpell((*accountResult)[0].GetUInt32(), (*accountResult)[1].GetBool(), false, false, (*accountResult)[2].GetBool(), true, (*accountResult)[3].GetBool());
        }
        while (accountResult->NextRow());
    }

    l_Times.push_back(getMSTime() - l_StartTime);

    _LoadAuras(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADAURAS), holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADAURAS_EFFECTS), time_diff);

    l_Times.push_back(getMSTime() - l_StartTime);

    // add ghost flag (must be after aura load: PLAYER_FIELD_PLAYER_FLAGS_GHOST set in aura)
    if (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
        m_deathState = DEAD;

    l_Times.push_back(getMSTime() - l_StartTime);

    // after spell load, learn rewarded spell if need also
    _LoadQuestStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
    _LoadQuestObjectiveStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_QUEST_OBJECTIVE_STATUS));
    _LoadQuestStatusRewarded(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUSREW));
    _LoadDailyQuestStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
    _LoadWeeklyQuestStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADWEEKLYQUESTSTATUS));
    _LoadSeasonalQuestStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADSEASONALQUESTSTATUS));
    _LoadMonthlyQuestStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_MONTHLY_QUEST_STATUS));
    _LoadRandomBGStatus(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADRANDOMBG));

    l_Times.push_back(getMSTime() - l_StartTime);

    // after spell and quest load
    InitTalentForLevel();
    l_Times.push_back(getMSTime() - l_StartTime);

    InitSpellForLevel();
    l_Times.push_back(getMSTime() - l_StartTime);

    learnDefaultSpells();
    l_Times.push_back(getMSTime() - l_StartTime);

    // must be before inventory (some items required reputation check)
    m_reputationMgr.LoadFromDB(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));

    _LoadInventory(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);

    if (IsVoidStorageUnlocked())
        _LoadVoidStorage(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADVOIDSTORAGE));

    m_VoidStorageLoaded = true;

    // update items with duration and realtime
    UpdateItemDuration(time_diff, true);

    l_Times.push_back(getMSTime() - l_StartTime);

    _LoadActions(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADACTIONS));

    // unread mails and next delivery time, actual mails not loaded
    _LoadMailInit(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));

    m_social = sSocialMgr->LoadFromDB(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow(), GetSession()->GetAccountId());

    // check PLAYER_CHOSEN_TITLE compatibility with PLAYER_FIELD_KNOWN_TITLES
    // note: PLAYER_FIELD_KNOWN_TITLES updated at quest status loaded
    uint32 curTitle = fields[43].GetUInt32();
    if (curTitle && !HasTitle(curTitle))
        curTitle = 0;

    SetUInt32Value(PLAYER_FIELD_PLAYER_TITLE, curTitle);

    // has to be called after last Relocate() in Player::LoadFromDB
    SetFallInformation(0, GetPositionZ());

    l_Times.push_back(getMSTime() - l_StartTime);

    _LoadSpellCooldowns(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
    _LoadChargesCooldowns(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_CHARGES_COOLDOWNS));
    _LoadCompletedChallenges(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOAD_COMPLETED_CHALLENGES));
    _LoadDailyLootsCooldowns(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_DAILY_LOOT_COOLDOWNS));

    l_Times.push_back(getMSTime() - l_StartTime);

    // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
    // Do now before stats re-calculation cleanup for ghost state unexpected auras
    if (!isAlive())
        RemoveAllAurasOnDeath();
    else
        RemoveAllAurasRequiringDeadTarget();

    // Command Demon
    RemoveAura(119904);

    //apply all stat bonuses from items and auras
    SetCanModifyStats(true);
    UpdateAllStats();

    // restore remembered power/health values (but not more max values)
    uint32 savedHealth = fields[46].GetUInt32();
    SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
    uint32 loadedPowers = 0;
    for (uint32 i = 0; i < MAX_POWERS; ++i)
    {
        if (GetPowerIndex(Powers(i), getClass()) != MAX_POWERS)
        {
            uint32 savedPower = fields[47+loadedPowers].GetUInt32();
            uint32 maxPower = GetUInt32Value(UNIT_FIELD_MAX_POWER + loadedPowers);
            SetPower(Powers(i), (savedPower > maxPower) ? maxPower : savedPower);
            if (++loadedPowers >= MAX_POWERS_PER_CLASS)
                break;
        }
    }

    for (; loadedPowers < MAX_POWERS_PER_CLASS; ++loadedPowers)
        SetUInt32Value(UNIT_FIELD_POWER + loadedPowers, 0);

    SetPower(POWER_ECLIPSE, 0);

    l_Times.push_back(getMSTime() - l_StartTime);

    // must be after loading spells and talents
    Tokenizer talentTrees(fields[26].GetString(), ' ', MAX_TALENT_SPECS);
    /*for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
    {
        if (i >= talentTrees.size())
            break;

        uint32 talentTree = atol(talentTrees[i]);
        if (sTalentTabStore.LookupEntry(talentTree))
            SetPrimaryTalentTree(i, talentTree);
        else if (i == GetActiveSpec())
            SetAtLoginFlag(AT_LOGIN_RESET_TALENTS); // invalid tree, reset talents
    }*/

    sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "The value of player %s after load item and aura is: ", m_name.c_str());
    outDebugValues();

    // GM state
    if (!AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()))
    {
        switch (sWorld->getIntConfig(CONFIG_GM_LOGIN_STATE))
        {
            default:
            case 0:                      break;             // disable
            case 1: SetGameMaster(true); break;             // enable
            case 2:                                         // save state
                if (extraflags & PLAYER_EXTRA_GM_ON)
                    SetGameMaster(true);
                break;
        }

        switch (sWorld->getIntConfig(CONFIG_GM_VISIBLE_STATE))
        {
            default:
            case 0: SetGMVisible(false); break;             // invisible
            case 1:                      break;             // visible
            case 2:                                         // save state
                if (extraflags & PLAYER_EXTRA_GM_INVISIBLE)
                    SetGMVisible(false);
                break;
        }

        switch (sWorld->getIntConfig(CONFIG_GM_CHAT))
        {
            default:
            case 0:                  break;                 // disable
            case 1: SetGMChat(true); break;                 // enable
            case 2:                                         // save state
                if (extraflags & PLAYER_EXTRA_GM_CHAT)
                    SetGMChat(true);
                break;
        }

        switch (sWorld->getIntConfig(CONFIG_GM_WHISPERING_TO))
        {
            default:
            case 0:                          break;         // disable
            case 1: SetAcceptWhispers(true); break;         // enable
            case 2:                                         // save state
                if (extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
                    SetAcceptWhispers(true);
                break;
        }
    }

    l_Times.push_back(getMSTime() - l_StartTime);

    // RaF stuff.
    m_grantableLevels = fields[64].GetUInt8();

    if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
        SetFlag(OBJECT_FIELD_DYNAMIC_FLAGS, UNIT_DYNFLAG_REFER_A_FRIEND);

    /// Commented due to action bar fix, need more research
    ///if (m_grantableLevels > 0)
    ///    SetByteValue(PLAYER_FIELD_LIFETIME_MAX_RANK, 1, 0x01);

    _LoadDeclinedNames(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));

    m_achievementMgr.CheckAllAchievementCriteria(this);

    _LoadEquipmentSets(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));

    if (mustResurrectFromUnlock)
        ResurrectPlayer(1, true);

    if (GmTicket* ticket = sTicketMgr->GetTicketByPlayer(GetGUID()))
        if (!ticket->IsClosed() && ticket->IsCompleted())
            ticket->SendResponse(GetSession());

    l_Times.push_back(getMSTime() - l_StartTime);

    // Set realmID
    SetUInt32Value(PLAYER_FIELD_VIRTUAL_PLAYER_REALM, g_RealmID);
    ReloadPetBattles();

    MS::Garrison::Manager * l_Garrison = new MS::Garrison::Manager(this);

    if (l_Garrison->Load(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_GARRISON), holder->GetPreparedResult(PLAYER_LOGIN_QUERY_GARRISON_BUILDINGS), holder->GetPreparedResult(PLAYER_LOGIN_QUERY_GARRISON_FOLLOWERS), holder->GetPreparedResult(PLAYER_LOGIN_QUERY_GARRISON_MISSIONS), holder->GetPreparedResult(PLAYER_LOGIN_QUERY_GARRISON_WORKORDERS)))
        m_Garrison = l_Garrison;
    else
        delete l_Garrison;

    _LoadGarrisonTavernDatas(holder->GetPreparedResult(PLAYER_LOGIN_QUERY_GARRISON_MISSIONS_TAVERNDATA));

    l_Times.push_back(getMSTime() - l_StartTime);
    RewardCompletedAchievementsIfNeeded();
    CheckTalentSpells();
    l_Times.push_back(getMSTime() - l_StartTime);

    if ((getMSTime() - l_StartTime) > 50)
    {
        sLog->outInfo(LOG_FILTER_PROFILING, "Player::LoadFromDB profiling =======");
        for (int32 l_I = 0; l_I < (int32)l_Times.size(); l_I++)
            sLog->outInfo(LOG_FILTER_PROFILING, "Index [%u] : %u ms", l_I, l_Times[l_I]);
        sLog->outInfo(LOG_FILTER_PROFILING, "====================================");

    }

    return true;
}

bool Player::isAllowedToLoot(const Creature* creature)
{
    if (!creature->isDead() || !creature->IsDamageEnoughForLootingAndReward())
        return false;

    if (HasPendingBind())
        return false;

    const Loot* loot = &creature->loot;
    if (loot->isLooted()) // nothing to loot or everything looted.
        return false;

    if (loot->AllowedPlayers.IsEnabled())
    {
        if (!loot->AllowedPlayers.HasPlayerGuid(GetGUID()))
            return false;
    }

    Group* thisGroup = GetGroup();
    if (!thisGroup)
        return this == creature->GetLootRecipient();
    else if (thisGroup != creature->GetLootRecipientGroup())
        return false;

    switch (thisGroup->GetLootMethod())
    {
        case FREE_FOR_ALL:
            return true;
        case ROUND_ROBIN:
        case MASTER_LOOT:
            // may only loot if the player is the loot roundrobin player
            // or if there are free/quest/conditional item for the player
            if (loot->RoundRobinPlayer == 0 || loot->RoundRobinPlayer == GetGUID())
                return true;

            return loot->hasItemFor(this);
        case GROUP_LOOT:
        case NEED_BEFORE_GREED:
            // may only loot if the player is the loot roundrobin player
            // or item over threshold (so roll(s) can be launched)
            // or if there are free/quest/conditional item for the player
            if (loot->RoundRobinPlayer == 0 || loot->RoundRobinPlayer == GetGUID())
                return true;

            if (loot->hasOverThresholdItem())
                return true;

            return loot->hasItemFor(this);
    }

    return false;
}

void Player::_LoadActions(PreparedQueryResult result)
{
    m_actionButtons.clear();

    if (result)
    {
        do
        {
            Field* fields = result->Fetch();
            uint8 button = fields[0].GetUInt8();
            uint32 action = fields[1].GetUInt32();
            uint8 type = fields[2].GetUInt8();

            if (ActionButton* ab = addActionButton(button, action, type))
                ab->uState = ACTIONBUTTON_UNCHANGED;
            else
            {
                // Will deleted in DB at next save (it can create data until save but marked as deleted)
                m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
            }
        }
        while (result->NextRow());
    }
}

void Player::_LoadAuras(PreparedQueryResult result, PreparedQueryResult resultEffect, uint32 timediff)
{
    sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Loading auras for player %u", GetGUIDLow());

    std::list<auraEffectData> auraEffectList;
    if (resultEffect)
    {
        do
        {
            Field* fields = resultEffect->Fetch();
            uint8 slot = fields[0].GetUInt8();
            uint8 effect = fields[1].GetUInt8();
            uint32 baseamount = fields[2].GetUInt32();
            uint32 amount = fields[3].GetUInt32();

            auraEffectList.push_back(auraEffectData(slot, effect, amount, baseamount));
        }
        while (resultEffect->NextRow());
    }

    /*                                                           0       1        2         3                 4         5      6       7         8              9            10
    QueryResult* result = CharacterDatabase.PQuery("SELECT caster_guid, spell, effect_mask, recalculate_mask, stackcount, amount0, amount1, amount2, base_amount0, base_amount1, base_amount2,
                                                        11          12          13
                                                    maxduration, remaintime, remaincharges FROM character_aura WHERE guid = '%u'", GetGUIDLow());
    */

    if (result)
    {
        do
        {
            Field* fields = result->Fetch();
            int32 damage[32];
            int32 baseDamage[32];
            uint64 caster_guid = fields[0].GetUInt64();
            uint8 slot = fields[1].GetUInt8();
            uint32 spellid = fields[2].GetUInt32();
            uint32 effmask = fields[3].GetUInt8();
            uint32 recalculatemask = fields[4].GetUInt8();
            uint8 stackcount = fields[5].GetUInt8();
            int32 maxduration = fields[6].GetInt32();
            int32 remaintime = fields[7].GetInt32();
            uint8 remaincharges = fields[8].GetUInt8();

            SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellid);
            if (!spellInfo)
            {
                sLog->outError(LOG_FILTER_PLAYER, "Unknown aura (spellid %u), ignore.", spellid);
                continue;
            }

            // negative effects should continue counting down after logout
            if (remaintime != -1 && !spellInfo->IsPositive())
            {
                if (remaintime/IN_MILLISECONDS <= int32(timediff))
                    continue;

                remaintime -= timediff*IN_MILLISECONDS;
            }

            // prevent wrong values of remaincharges
            if (spellInfo->ProcCharges)
            {
                // we have no control over the order of applying auras and modifiers allow auras
                // to have more charges than value in SpellInfo
                if (remaincharges <= 0/* || remaincharges > spellproto->procCharges*/)
                    remaincharges = spellInfo->ProcCharges;
            }
            else
                remaincharges = 0;

            for(std::list<auraEffectData>::iterator itr = auraEffectList.begin(); itr != auraEffectList.end(); ++itr)
            {
                if (itr->_slot == slot)
                {
                    damage[itr->_effect] = itr->_amount;
                    baseDamage[itr->_effect] = itr->_baseamount;
                }
            }

            Aura* aura = Aura::TryCreate(spellInfo, effmask, this, NULL, &baseDamage[0], NULL, caster_guid);
            if (aura != nullptr)
            {
                if (!aura->CanBeSaved())
                {
                    aura->Remove();
                    continue;
                }

                aura->SetLoadedState(maxduration, remaintime, remaincharges, stackcount, recalculatemask, &damage[0]);
                aura->ApplyForTargets();
                sLog->outInfo(LOG_FILTER_PLAYER, "Added aura spellid %u, effectmask %u", spellInfo->Id, effmask);
            }
        }
        while (result->NextRow());
    }
}

void Player::_LoadGlyphAuras()
{
    for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
    {
        if (uint32 glyph = GetGlyph(GetActiveSpec(), i))
        {
            if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
            {
                if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
                {
                    if (gp->TypeFlags == gs->TypeFlags)
                    {
                        CastSpell(this, gp->SpellId, true);
                        continue;
                    }
                    else
                        sLog->outError(LOG_FILTER_PLAYER, "Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
                }
                else
                    sLog->outError(LOG_FILTER_PLAYER, "Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
            }
            else
                sLog->outError(LOG_FILTER_PLAYER, "Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);

            // On any error remove glyph
            SetGlyph(i, 0);
        }
    }
}

bool Player::HasGlyph(uint32 spell_id)
{
    for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
        if (uint32 glyph = GetGlyph(GetActiveSpec(), i))
            if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph))
                if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
                    if (gp->TypeFlags == gs->TypeFlags && gp->SpellId == spell_id)
                        return true;

    return false;
}

void Player::LoadCorpse()
{
    if (isAlive())
        sObjectAccessor->ConvertCorpseForPlayer(GetGUID());
    else
    {
        if (Corpse* corpse = GetCorpse())
            ApplyModFlag(PLAYER_FIELD_LIFETIME_MAX_RANK, PLAYER_LOCAL_FLAG_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable());
        else
            //Prevent Dead Player login without corpse
            ResurrectPlayer(0.5f);
    }
}

void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff)
{
    //QueryResult* result = CharacterDatabase.PQuery("SELECT data, text, bag, slot, item, item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag, slot", GetGUIDLow());
    //NOTE: the "order by `bag`" is important because it makes sure
    //the bagMap is filled before items in the bags are loaded
    //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
    //expected to be equipped before offhand items (TODO: fixme)

    if (result)
    {
        uint32 zoneId = GetZoneId(true);

        std::map<uint32, Bag*> bagMap;                                  // fast guid lookup for bags
        std::map<uint32, Item*> invalidBagMap;                          // fast guid lookup for bags
        std::list<Item*> problematicItems;
        SQLTransaction trans = CharacterDatabase.BeginTransaction();

        // Prevent items from being added to the queue while loading
        m_itemUpdateQueueBlocked = true;
        do
        {
            Field* fields = result->Fetch();
            if (Item* item = _LoadItem(trans, zoneId, timeDiff, fields))
            {
                uint32 bagGuid  = fields[15].GetUInt32();
                uint8  slot     = fields[16].GetUInt8();

                uint8 err = EQUIP_ERR_OK;
                // Item is not in bag
                if (!bagGuid)
                {
                    item->SetContainer(NULL);
                    item->SetSlot(slot);

                    if (IsInventoryPos(INVENTORY_SLOT_BAG_0, slot))
                    {
                        ItemPosCountVec dest;
                        err = CanStoreItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false);
                        if (err == EQUIP_ERR_OK)
                            item = StoreItem(dest, item, true);
                    }
                    else if (IsEquipmentPos(INVENTORY_SLOT_BAG_0, slot))
                    {
                        uint16 dest;
                        err = CanEquipItem(slot, dest, item, false, false);
                        if (err == EQUIP_ERR_OK)
                            QuickEquipItem(dest, item);
                    }
                    else if (IsBankPos(INVENTORY_SLOT_BAG_0, slot))
                    {
                        ItemPosCountVec dest;
                        err = CanBankItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false, false);
                        if (err == EQUIP_ERR_OK)
                            item = BankItem(dest, item, true);
                    }
                    else if (IsReagentBankPos(INVENTORY_SLOT_BAG_0, slot))
                    {
                        ItemPosCountVec dest;
                        err = CanReagentBankItem(INVENTORY_SLOT_BAG_0, slot, dest, item, false);
                        if (err == EQUIP_ERR_OK)
                            item = BankItem(dest, item, true);
                    }

                    // Remember bags that may contain items in them
                    if (err == EQUIP_ERR_OK)
                    {
                        if (IsBagPos(item->GetPos()))
                            if (Bag* pBag = item->ToBag())
                                bagMap[item->GetGUIDLow()] = pBag;
                    }
                    else
                        if (IsBagPos(item->GetPos()))
                            if (item->IsBag())
                                invalidBagMap[item->GetGUIDLow()] = item;
                }
                else
                {
                    item->SetSlot(NULL_SLOT);
                    // Item is in the bag, find the bag
                    std::map<uint32, Bag*>::iterator itr = bagMap.find(bagGuid);
                    if (itr != bagMap.end())
                    {
                        ItemPosCountVec dest;
                        err = CanStoreItem(itr->second->GetSlot(), slot, dest, item);
                        if (err == EQUIP_ERR_OK)
                            item = StoreItem(dest, item, true);
                    }
                    else if (invalidBagMap.find(bagGuid) != invalidBagMap.end())
                    {
                        std::map<uint32, Item*>::iterator itr = invalidBagMap.find(bagGuid);
                        if (std::find(problematicItems.begin(), problematicItems.end(),itr->second) != problematicItems.end())
                            err = EQUIP_ERR_INTERNAL_BAG_ERROR;
                    }
                    else
                    {
                        sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which doesnt have a valid bag (Bag GUID: %u, slot: %u). Possible cheat?",
                            GetGUIDLow(), GetName(), item->GetGUIDLow(), item->GetEntry(), bagGuid, slot);
                        item->DeleteFromInventoryDB(trans);
                        delete item;
                        continue;
                    }

                }

                // Item's state may have changed after storing
                if (err == EQUIP_ERR_OK)
                    item->SetState(ITEM_UNCHANGED, this);
                else
                {
                    sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) which can't be loaded into inventory (Bag GUID: %u, slot: %u) by reason %u. Item will be sent by mail.",
                        GetGUIDLow(), GetName(), item->GetGUIDLow(), item->GetEntry(), bagGuid, slot, err);
                    item->DeleteFromInventoryDB(trans);
                    problematicItems.push_back(item);
                }

                if (item->GetTemplate()->Quality == ITEM_QUALITY_HEIRLOOM)
                    if (HeirloomEntry const* l_HeirloomEntry = GetHeirloomEntryByItemID(item->GetTemplate()->ItemId))
                        AddHeirloom(l_HeirloomEntry, item->HasCustomFlags(ItemCustomFlags::FromStore));
            }
        }
        while (result->NextRow());

        m_itemUpdateQueueBlocked = false;

        // Send problematic items by mail
        while (!problematicItems.empty())
        {
            std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);

            MailDraft draft(subject, "There were problems with equipping item(s).");
            for (uint8 i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
            {
                draft.AddItem(problematicItems.front());
                problematicItems.pop_front();
            }
            draft.SendMailTo(trans, this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);
        }
        CharacterDatabase.CommitTransaction(trans);
    }
    //if (isAlive())
    _ApplyAllItemMods();
}

void Player::_LoadVoidStorage(PreparedQueryResult result)
{
    if (!result)
        return;

    do
    {
        // SELECT itemid, itemEntry, slot, creatorGuid FROM character_void_storage WHERE playerGuid = ?
        Field* fields = result->Fetch();

        uint64 itemId = fields[0].GetUInt64();
        uint32 itemEntry = fields[1].GetUInt32();
        uint8 slot = fields[2].GetUInt8();
        uint32 creatorGuid = fields[3].GetUInt32();
        uint32 randomProperty = fields[4].GetUInt32();
        uint32 suffixFactor = fields[5].GetUInt32();
        Tokenizer l_BonusToken(fields[6].GetString(), ' ');

        if (!itemId)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadVoidStorage - Player (GUID: %u, name: %s) has an item with an invalid id (item id: " UI64FMTD ", entry: %u).", GetGUIDLow(), GetName(), itemId, itemEntry);
            continue;
        }

        if (!sObjectMgr->GetItemTemplate(itemEntry))
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadVoidStorage - Player (GUID: %u, name: %s) has an item with an invalid entry (item id: " UI64FMTD ", entry: %u).", GetGUIDLow(), GetName(), itemId, itemEntry);
            continue;
        }

        if (slot >= VOID_STORAGE_MAX_SLOT)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadVoidStorage - Player (GUID: %u, name: %s) has an item with an invalid slot (item id: " UI64FMTD ", entry: %u, slot: %u).", GetGUIDLow(), GetName(), itemId, itemEntry, slot);
            continue;
        }

        std::vector<uint32> l_Bonuses;
        for (uint8 l_I = 0; l_I < l_BonusToken.size(); ++l_I)
            l_Bonuses.push_back(atoi(l_BonusToken[l_I]));

        if (!sObjectMgr->GetPlayerByLowGUID(creatorGuid))
            creatorGuid = 0;

        _voidStorageItems[slot] = new VoidStorageItem(itemId, itemEntry, creatorGuid, randomProperty, suffixFactor, l_Bonuses);
    }
    while (result->NextRow());
}

Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, Field* fields)
{
    Item* item = NULL;
    uint32 itemGuid  = fields[17].GetUInt32();
    uint32 itemEntry = fields[18].GetUInt32();
    if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemEntry))
    {
        bool remove = false;
        item = NewItemOrBag(proto);
        if (item->LoadFromDB(itemGuid, GetGUID(), fields, itemEntry))
        {
            PreparedStatement* stmt = NULL;

            // Do not allow to have item limited to another map/zone in alive state
            if (isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(), zoneId))
            {
                sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s', map: %u) has item (GUID: %u, entry: %u) limited to another map (%u). Deleting item.",
                    GetGUIDLow(), GetName(), GetMapId(), item->GetGUIDLow(), item->GetEntry(), zoneId);
                remove = true;
            }
            // "Conjured items disappear if you are logged out for more than 15 minutes"
            else if (timeDiff > 15 * MINUTE && proto->Flags & ITEM_FLAG_CONJURED)
            {
                sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s', diff: %u) has conjured item (GUID: %u, entry: %u) with expired lifetime (15 minutes). Deleting item.",
                    GetGUIDLow(), GetName(), timeDiff, item->GetGUIDLow(), item->GetEntry());
                remove = true;
            }
            else if (item->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE))
            {
                if (item->GetPlayedTime() > (2 * HOUR))
                {
                    sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with expired refund time (%u). Deleting refund data and removing refundable flag.",
                        GetGUIDLow(), GetName(), item->GetGUIDLow(), item->GetEntry(), item->GetPlayedTime());

                    stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_REFUND_INSTANCE);
                    stmt->setUInt32(0, item->GetGUIDLow());
                    trans->Append(stmt);

                    item->RemoveFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE);
                }
                else
                {
                    uint64 l_PlayerGUID = GetGUID();

                    PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEM_REFUNDS);
                    l_Statement->setUInt32(0, item->GetGUIDLow());
                    l_Statement->setUInt32(1, GetGUIDLow());

                    CharacterDatabase.AsyncQuery(l_Statement, [itemGuid, l_PlayerGUID](PreparedQueryResult p_Result) -> void
                    {
                        Player* l_Player = sObjectAccessor->FindPlayer(l_PlayerGUID);
                        if (l_Player == nullptr)
                            return;

                        Item* l_ItemRetreive = l_Player->GetItemByGuid(MAKE_NEW_GUID(itemGuid, 0, HIGHGUID_ITEM));
                        if (l_ItemRetreive == nullptr)
                            return;

                        if (p_Result)
                        {
                            l_ItemRetreive->SetRefundRecipient((*p_Result)[0].GetUInt32());
                            l_ItemRetreive->SetPaidMoney((*p_Result)[1].GetUInt32());
                            l_ItemRetreive->SetPaidExtendedCost((*p_Result)[2].GetUInt16());
                            l_Player->AddRefundReference(l_ItemRetreive->GetGUIDLow());
                        }
                        else
                        {
                            sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with refundable flags, but without data in item_refund_instance. Removing flag.",
                                l_Player->GetGUIDLow(), l_Player->GetName(), l_ItemRetreive->GetGUIDLow(), l_ItemRetreive->GetEntry());
                            l_ItemRetreive->RemoveFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE);
                        }
                    });
                }
            }
            else if (item->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE))
            {
                uint64 l_PlayerGUID = GetGUID();

                PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEM_BOP_TRADE);
                l_Statement->setUInt32(0, item->GetGUIDLow());

                CharacterDatabase.AsyncQuery(l_Statement, [itemGuid, l_PlayerGUID](PreparedQueryResult p_Result) -> void
                {
                    Player* l_Player = sObjectAccessor->FindPlayer(l_PlayerGUID);
                    if (l_Player == nullptr)
                        return;

                    Item* l_ItemRetreive = l_Player->GetItemByGuid(MAKE_NEW_GUID(itemGuid, 0, HIGHGUID_ITEM));
                    if (l_ItemRetreive == nullptr)
                        return;

                    if (p_Result)
                    {
                        std::string strGUID = (*p_Result)[0].GetString();
                        Tokenizer GUIDlist(strGUID, ' ');
                        AllowedLooterSet looters;
                        for (Tokenizer::const_iterator itr = GUIDlist.begin(); itr != GUIDlist.end(); ++itr)
                            looters.insert(atol(*itr));
                        l_ItemRetreive->SetSoulboundTradeable(looters);
                        l_Player->AddTradeableItem(l_ItemRetreive);
                    }
                    else
                    {
                        sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Player::_LoadInventory: player (GUID: %u, name: '%s') has item (GUID: %u, entry: %u) with ITEM_FIELD_FLAG_BOP_TRADEABLE flag, but without data in item_soulbound_trade_data. Removing flag.",
                            l_Player->GetGUIDLow(), l_Player->GetName(), l_ItemRetreive->GetGUIDLow(), l_ItemRetreive->GetEntry());
                        l_ItemRetreive->RemoveFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE);
                    }
                });
            }
            else if (proto->HolidayId)
            {
                remove = true;
                GameEventMgr::GameEventDataMap const& events = sGameEventMgr->GetEventMap();
                GameEventMgr::ActiveEvents const& activeEventsList = sGameEventMgr->GetActiveEventList();
                for (GameEventMgr::ActiveEvents::const_iterator itr = activeEventsList.begin(); itr != activeEventsList.end(); ++itr)
                {
                    if (uint32(events[*itr].holiday_id) == proto->HolidayId)
                    {
                        remove = false;
                        break;
                    }
                }
            }
        }
        else
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has broken item (GUID: %u, entry: %u) in inventory. Deleting item.",
                GetGUIDLow(), GetName(), itemGuid, itemEntry);
            remove = true;
        }
        // Remove item from inventory if necessary
        if (remove)
        {
            Item::DeleteFromInventoryDB(trans, itemGuid);
            item->FSetState(ITEM_REMOVED);
            item->SaveToDB(trans);                           // it also deletes item object!
            item = NULL;
        }
    }
    else
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadInventory: player (GUID: %u, name: '%s') has unknown item (entry: %u) in inventory. Deleting item.",
            GetGUIDLow(), GetName(), itemEntry);
        /* Delete de cette foutue fonction, jamais tu ne delete des items !
        Item::DeleteFromInventoryDB(trans, itemGuid);
        Item::DeleteFromDB(trans, itemGuid);
        */
    }
    return item;
}

// load mailed item which should receive current player
void Player::_LoadMailedItems(PreparedQueryResult p_MailedItems)
{
    // data needs to be at first place for Item::LoadFromDB
    if (!p_MailedItems)
        return;

    do
    {
        Field* l_Fields = p_MailedItems->Fetch();

        uint32 l_ItemGuid     = l_Fields[15].GetUInt32();
        uint32 l_ItemTemplate = l_Fields[16].GetUInt32();
        uint32 l_MailId       = l_Fields[18].GetUInt32();

        Mail* l_Mail = GetMail(l_MailId);
        if (l_Mail == nullptr)
            continue;

        l_Mail->AddItem(l_ItemGuid, l_ItemTemplate);

        ItemTemplate const* l_Proto = sObjectMgr->GetItemTemplate(l_ItemTemplate);

        if (!l_Proto)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), l_ItemGuid, l_ItemTemplate, l_Mail->messageID);

            PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_MAIL_ITEM);
            l_Statement->setUInt32(0, l_ItemGuid);
            CharacterDatabase.Execute(l_Statement);

            l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
            l_Statement->setUInt32(0, l_ItemGuid);
            CharacterDatabase.Execute(l_Statement);
            continue;
        }

        Item* l_Item = NewItemOrBag(l_Proto);
        if (!l_Item->LoadFromDB(l_ItemGuid, MAKE_NEW_GUID(l_Fields[17].GetUInt32(), 0, HIGHGUID_PLAYER), l_Fields, l_ItemTemplate))
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", l_Mail->messageID, l_ItemGuid);

            PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM);
            l_Statement->setUInt32(0, l_ItemGuid);
            CharacterDatabase.Execute(l_Statement);

            l_Item->FSetState(ITEM_REMOVED);

            SQLTransaction l_Tmp = SQLTransaction(NULL);
            l_Item->SaveToDB(l_Tmp);                               // it also deletes item object !
            continue;
        }

        AddMItem(l_Item);
    }
    while (p_MailedItems->NextRow());
}

void Player::_LoadMailInit(PreparedQueryResult resultUnread, PreparedQueryResult resultDelivery)
{
    //set a count of unread mails
    //QueryResult* resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid), (uint64)cTime);
    if (resultUnread)
        unReadMails = uint8((*resultUnread)[0].GetUInt64());

    // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
    //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
    if (resultDelivery)
        m_nextMailDelivereTime = time_t((*resultDelivery)[0].GetUInt32());
}

void Player::_LoadMail(PreparedQueryResult p_MailResult)
{
    m_mail.clear();

    if (p_MailResult)
    {
        do
        {
            Field* fields = p_MailResult->Fetch();
            Mail* m = new Mail;

            m->messageID      = fields[0].GetUInt32();
            m->messageType    = fields[1].GetUInt8();
            m->sender         = fields[2].GetUInt32();
            m->receiver       = fields[3].GetUInt32();
            m->subject        = fields[4].GetString();
            m->body           = fields[5].GetString();
            bool has_items    = fields[6].GetBool(); ///< hasitem is never read 01/18/16<--- Variable 'has_items' is assigned a value that is never used.
            m->expire_time    = time_t(fields[7].GetUInt32());
            m->deliver_time   = time_t(fields[8].GetUInt32());
            m->money          = fields[9].GetUInt64();
            m->COD            = fields[10].GetUInt64();
            m->checked        = fields[11].GetUInt8();
            m->stationery     = fields[12].GetUInt8();
            m->mailTemplateId = fields[13].GetInt16();

            if (m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
            {
                sLog->outError(LOG_FILTER_PLAYER, "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
                m->mailTemplateId = 0;
            }

            m->state = MAIL_STATE_UNCHANGED;

            m_mail.push_back(m);
        }
        while (p_MailResult->NextRow());
    }
}

void Player::LoadPet(PreparedQueryResult result)
{
    //fixme: the pet should still be loaded if the player is not in world
    // just not added to the map
    if (IsInWorld() && result)
    {
        Field* fields = result->Fetch();
        PetQueryHolder* queryHolder = new PetQueryHolder(fields[0].GetUInt32(), result);
        if (!queryHolder->Initialize())
        {
            delete queryHolder;
            return;
        }

        _petLoginCallback = CharacterDatabase.DelayQueryHolder((SQLQueryHolder*)queryHolder);
    }
}

void Player::_LoadQuestStatus(PreparedQueryResult result)
{
    uint16 slot = 0;

    ////                                                       0      1       2        3
    //QueryResult* result = CharacterDatabase.PQuery("SELECT quest, status, explored, timer, FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());

    if (result)
    {
        do
        {
            Field* fields = result->Fetch();

            uint32 quest_id = fields[0].GetUInt32();
                                                            // used to be new, no delete?
            Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
            if (quest)
            {
                // find or create
                QuestStatusData& questStatusData = m_QuestStatus[quest_id];

                uint8 qstatus = fields[1].GetUInt8();
                if (qstatus < MAX_QUEST_STATUS)
                    questStatusData.Status = QuestStatus(qstatus);
                else
                {
                    questStatusData.Status = QUEST_STATUS_INCOMPLETE;
                    sLog->outError(LOG_FILTER_PLAYER, "Player %s (GUID: %u) has invalid quest %d status (%u), replaced by QUEST_STATUS_INCOMPLETE(3).",
                        GetName(), GetGUIDLow(), quest_id, qstatus);
                }

                questStatusData.Explored = (fields[2].GetUInt8() > 0);

                time_t quest_time = time_t(fields[3].GetUInt32());

                if (quest->HasSpecialFlag(QUEST_SPECIAL_FLAGS_TIMED) && !GetQuestRewardStatus(quest_id))
                {
                    AddTimedQuest(quest_id);

                    if (quest_time <= sWorld->GetGameTime())
                        questStatusData.Timer = 1;
                    else
                        questStatusData.Timer = uint32((quest_time - sWorld->GetGameTime()) * IN_MILLISECONDS);
                }
                else
                    quest_time = 0;


                // add to quest log
                if (slot < MAX_QUEST_LOG_SIZE && questStatusData.Status != QUEST_STATUS_NONE)
                {
                    SetQuestSlot(slot, quest_id, uint32(quest_time)); // cast can't be helped

                    if (questStatusData.Status == QUEST_STATUS_COMPLETE)
                        SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
                    else if (questStatusData.Status == QUEST_STATUS_FAILED)
                        SetQuestSlotState(slot, QUEST_STATE_FAIL);

                    ++slot;
                }

                sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.Status, quest_id, GetGUIDLow());
            }
        }
        while (result->NextRow());
    }

    // clear quest log tail
    for (uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i)
        SetQuestSlot(i, 0);
}

void Player::_LoadQuestObjectiveStatus(PreparedQueryResult result)
{
    if (result)
    {
        do
        {
            Field* fields = result->Fetch();

            uint32 objectiveId  = fields[0].GetUInt32();
            uint32 amount       = fields[1].GetUInt32();

            if (!sObjectMgr->QuestObjectiveExists(objectiveId))
            {
                sLog->outError(LOG_FILTER_PLAYER, "Player %s (%u) has invalid Quest Objective Id %u in Quest Objective status data! Skipping.", GetName(), GetGUIDLow(), objectiveId);
                continue;
            }

            for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
            {
                uint32 questId = GetQuestSlotQuestId(i);
                if (!questId)
                    continue;

                uint32 objectiveQuestId = sObjectMgr->GetQuestObjectiveQuestId(objectiveId);
                if (questId != objectiveQuestId)
                    continue;

                // Quest existence is checked on Quest Objective load, no issue should arise
                QuestObjective const* objective = sObjectMgr->GetQuestTemplate(objectiveQuestId)->GetQuestObjective(objectiveId);

                SetQuestSlotCounter(i, objective->Index, amount);
                m_questObjectiveStatus.insert(std::make_pair(objectiveId, amount));

                if (objective->Type == QUEST_OBJECTIVE_TYPE_CRITERIA_TREE && (uint32)objective->Amount == amount)
                    SetQuestSlotState(i, QUEST_STATE_OBJ_0_COMPLETE << objective->Index);

                break;
            }
        } while (result->NextRow());
    }
}

void Player::_LoadQuestStatusRewarded(PreparedQueryResult result)
{
    // SELECT quest FROM character_queststatus_rewarded WHERE guid = ?

    if (result)
    {
        do
        {
            Field* fields = result->Fetch();

            uint32 quest_id = fields[0].GetUInt32();
                                                            // used to be new, no delete?
            Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
            if (quest)
            {
                // learn rewarded spell if unknown
                learnQuestRewardedSpells(quest);

                // set rewarded title if any
                if (quest->GetCharTitleId())
                {
                    if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(quest->GetCharTitleId()))
                        SetTitle(titleEntry);
                }

                /// Skip loading special quests - they are also added to rewarded quests but only once and remain there forever
                /// instead add them separately from load daily/weekly/monthly/seasonal
                if (!quest->IsDailyOrWeekly() && !quest->IsMonthly() && !quest->IsSeasonal())
                {
                    if (uint32 l_QuestBit = GetQuestUniqueBitFlag(quest_id))
                        SetQuestBit(l_QuestBit, true);
                }

                if (uint32 talents = quest->GetBonusTalents())
                    AddQuestRewardedTalentCount(talents);
            }

            m_RewardedQuests.insert(quest_id);
        }
        while (result->NextRow());
    }
}

void Player::_LoadDailyQuestStatus(PreparedQueryResult result)
{
    m_dailyQuestStorage.clear();

    m_DFQuests.clear();

    //QueryResult* result = CharacterDatabase.PQuery("SELECT quest, time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());

    if (result)
    {
        uint32 quest_daily_idx = 0;
        do
        {
            Field* fields = result->Fetch();
            if (Quest const* qQuest = sObjectMgr->GetQuestTemplate(fields[0].GetUInt32()))
            {
                if (qQuest->IsDFQuest())
                {
                    m_DFQuests.insert(qQuest->GetQuestId());
                    m_lastDailyQuestTime = time_t(fields[1].GetUInt32());
                    continue;
                }
            }

            uint32 quest_id = fields[0].GetUInt32();

            // save _any_ from daily quest times (it must be after last reset anyway)
            m_lastDailyQuestTime = time_t(fields[1].GetUInt32());

            Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
            if (!quest)
                continue;

            m_dailyQuestStorage.insert(quest_id);
            if (++quest_daily_idx < DynamicFields::Count)
                SetDynamicValue(PLAYER_DYNAMIC_FIELD_DAILY_QUESTS_COMPLETED, quest_daily_idx++, quest_id);

            if (uint32 questBit = GetQuestUniqueBitFlag(quest_id))
                SetQuestBit(questBit , true);

            sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Daily quest (%u) cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
        }
        while (result->NextRow());
    }

    m_DailyQuestChanged = false;
}

void Player::_LoadWeeklyQuestStatus(PreparedQueryResult result)
{
    m_weeklyquests.clear();

    if (result)
    {
        do
        {
            Field* fields = result->Fetch();
            uint32 quest_id = fields[0].GetUInt32();
            Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
            if (!quest)
                continue;

            m_weeklyquests.insert(quest_id);

            if (uint32 questBit = GetQuestUniqueBitFlag(quest_id))
                SetQuestBit(questBit, true);

            sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Weekly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
        }
        while (result->NextRow());
    }

    m_WeeklyQuestChanged = false;
}

void Player::_LoadSeasonalQuestStatus(PreparedQueryResult result)
{
    m_seasonalquests.clear();

    if (result)
    {
        do
        {
            Field* fields = result->Fetch();
            uint32 quest_id = fields[0].GetUInt32();
            uint32 event_id = fields[1].GetUInt32();
            Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
            if (!quest)
                continue;

            m_seasonalquests[event_id].insert(quest_id);

            if (uint32 questBit = GetQuestUniqueBitFlag(quest_id))
                SetQuestBit(questBit, true);

            sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Seasonal quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
        }
        while (result->NextRow());
    }

    m_SeasonalQuestChanged = false;
}

void Player::_LoadMonthlyQuestStatus(PreparedQueryResult result)
{
    m_monthlyquests.clear();

    if (result)
    {
        do
        {
            Field* fields = result->Fetch();
            uint32 quest_id = fields[0].GetUInt32();
            Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
            if (!quest)
                continue;

            m_monthlyquests.insert(quest_id);

            if (uint32 questBit = GetQuestUniqueBitFlag(quest_id))
                SetQuestBit(questBit, true);

            sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "Monthly quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
        }
        while (result->NextRow());
    }

    m_MonthlyQuestChanged = false;
}

void Player::_LoadSpells(PreparedQueryResult result)
{
    if (result)
    {
        do
        {
            Field* fields = result->Fetch();

            uint32 l_SpellID = fields[0].GetUInt32();

            for (uint32 l_I = 0; l_I < sBattlePetSpeciesStore.GetNumRows(); l_I++)
            {
                BattlePetSpeciesEntry const* speciesInfo = sBattlePetSpeciesStore.LookupEntry(l_I);

                if (speciesInfo && speciesInfo->spellId == l_SpellID)
                {
                    m_OldPetBattleSpellToMerge.push_back(std::make_pair(l_SpellID, speciesInfo->id));
                    break;
                }

            }

            addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool(), true, fields[3].GetBool());
        }
        while (result->NextRow());
    }
}

void Player::_LoadGarrisonTavernDatas(PreparedQueryResult p_Result)
{
    MS::Garrison::Manager* l_GarrisonMgr = GetGarrison();

    if (l_GarrisonMgr == nullptr)
        return;

    if (p_Result)
    {
        do
        {
            Field* fields = p_Result->Fetch();

            uint32 l_NpcEntry = fields[1].GetUInt32();
            l_GarrisonMgr->SetGarrisonTavernData(l_NpcEntry);
        }
        while (p_Result->NextRow());
    }
    else
    {

        if (l_GarrisonMgr->HasActiveBuilding(MS::Garrison::Buildings::LunarfallInn_FrostwallTavern_Level1))
        {
            if (roll_chance_i(50))
            {
                uint32 l_Entry = MS::Garrison::TavernDatas::g_QuestGiverEntries[urand(0, MS::Garrison::TavernDatas::g_QuestGiverEntries.size() - 1)];

                l_GarrisonMgr->CleanGarrisonTavernData();
                l_GarrisonMgr->AddGarrisonTavernData(l_Entry);
            }
            else
            {
                uint32 l_FirstEntry  = MS::Garrison::TavernDatas::g_QuestGiverEntries[urand(0, MS::Garrison::TavernDatas::g_QuestGiverEntries.size() - 1)];
                uint32 l_SecondEntry = 0;

                do
                    l_SecondEntry = MS::Garrison::TavernDatas::g_QuestGiverEntries[urand(0, MS::Garrison::TavernDatas::g_QuestGiverEntries.size() - 1)];
                while (l_SecondEntry == l_FirstEntry);

                l_GarrisonMgr->CleanGarrisonTavernData();
                l_GarrisonMgr->AddGarrisonTavernData(l_FirstEntry);
                l_GarrisonMgr->AddGarrisonTavernData(l_SecondEntry);
            }
        }
    }
}

void Player::_LoadGroup(PreparedQueryResult result)
{
    //QueryResult* result = CharacterDatabase.PQuery("SELECT guid FROM group_member WHERE memberGuid=%u", GetGUIDLow());
    if (result)
    {
        if (Group* group = sGroupMgr->GetGroupByDbStoreId((*result)[0].GetUInt32()))
        {
            uint8 subgroup = group->GetMemberGroup(GetGUID());
            SetGroup(group, subgroup);
            if (getLevel() >= LEVELREQUIREMENT_HEROIC)
            {
                // the group leader may change the instance difficulty while the player is offline
                SetDungeonDifficultyID(group->GetDungeonDifficultyID());
                SetRaidDifficultyID(group->GetRaidDifficultyID());
                SetLegacyRaidDifficultyID(group->GetLegacyRaidDifficultyID());
            }
        }
    }
}

void Player::_LoadBoundInstances(PreparedQueryResult result)
{
    for (uint8 i = 0; i < Difficulty::MaxDifficulties; ++i)
        m_boundInstances[i].clear();

    Group* group = GetGroup();

    //QueryResult* result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
    if (result)
    {
        do
        {
            Field* fields = result->Fetch();

            bool perm = fields[1].GetBool();
            uint32 mapId = fields[2].GetUInt16();
            uint32 instanceId = fields[0].GetUInt32();
            uint8 difficulty = fields[3].GetUInt8();

            time_t resetTime = time_t(fields[4].GetUInt32());
            // the resettime for normal instances is only saved when the InstanceSave is unloaded
            // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
            // and in that case it is not used

            bool deleteInstance = false;

            MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
            if (!mapEntry || !mapEntry->IsDungeon())
            {
                sLog->outError(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
                deleteInstance = true;
            }
            else if (difficulty >= Difficulty::MaxDifficulties)
            {
                sLog->outError(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
                deleteInstance = true;
            }
            else
            {
                MapDifficulty const* mapDiff = GetMapDifficultyData(mapId, Difficulty(difficulty));
                if (!mapDiff)
                {
                    sLog->outError(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
                    deleteInstance = true;
                }
                else if (!perm && group)
                {
                    sLog->outError(LOG_FILTER_PLAYER, "_LoadBoundInstances: player %s(%d) is in group %d but has a non-permanent character bind to map %d, %d, %d", GetName(), GetGUIDLow(), GUID_LOPART(group->GetGUID()), mapId, instanceId, difficulty);
                    deleteInstance = true;
                }
            }

            if (deleteInstance)
            {
                PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);

                stmt->setUInt32(0, GetGUIDLow());
                stmt->setUInt32(1, instanceId);

                CharacterDatabase.Execute(stmt);

                continue;
            }

            // since non permanent binds are always solo bind, they can always be reset
            if (InstanceSave* save = sInstanceSaveMgr->AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true))
               BindToInstance(save, perm, true);
        }
        while (result->NextRow());
    }
}

InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
{
    // some instances only have one difficulty
    MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(mapid, difficulty);
    if (!mapDiff)
        return NULL;

    BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
    if (itr != m_boundInstances[difficulty].end())
        return &itr->second;
    else
        return NULL;
}

InstanceSave* Player::GetInstanceSave(uint32 p_MapID)
{
    MapEntry const     * l_MapEntry = sMapStore.LookupEntry(p_MapID);
    InstancePlayerBind * l_Bind     = GetBoundInstance(p_MapID, GetDifficultyID(l_MapEntry));
    InstanceSave       * l_Save     = l_Bind ? l_Bind->save : NULL;

    if (!l_Bind || !l_Bind->perm)
    {
        if (Group* l_Group = GetGroup())
        {
            if (InstanceGroupBind* l_GroupBind = l_Group->GetBoundInstance(this))
                l_Save = l_GroupBind->save;
        }
    }

    if (!l_Bind || !l_Bind->perm)
    {
        if (Group* l_Group = GetGroup())
        {
            if (InstanceGroupBind* l_GroupBind = l_Group->GetBoundInstance(this))
                l_Save = l_GroupBind->save;
        }
    }

    return l_Save;
}

void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
{
    BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
    UnbindInstance(itr, difficulty, unload);
}

void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
{
    if (itr != m_boundInstances[difficulty].end())
    {
        if (!unload)
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INSTANCE_BY_INSTANCE_GUID);

            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt32(1, itr->second.save->GetInstanceId());

            CharacterDatabase.Execute(stmt);
        }

        if (itr->second.perm)
            GetSession()->SendCalendarRaidLockout(itr->second.save, false);

        itr->second.save->RemovePlayer(this);               // save can become invalid
        m_boundInstances[difficulty].erase(itr++);
    }
}

InstancePlayerBind* Player::BindToInstance(InstanceSave* p_InstanceSave, bool p_Permanent, bool p_Load)
{
    if (p_InstanceSave && p_InstanceSave->GetDifficultyID() != Difficulty::DifficultyRaidLFR && p_InstanceSave->GetDifficultyID() != Difficulty::DifficultyRaidTool)
    {
        InstancePlayerBind& l_InstanceBind = m_boundInstances[p_InstanceSave->GetDifficultyID()][p_InstanceSave->GetMapId()];
        if (l_InstanceBind.save)
        {
            // update the save when the group kills a boss
            if (p_Permanent != l_InstanceBind.perm || p_InstanceSave != l_InstanceBind.save)
            {
                if (!p_Load)
                {
                    PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_INSTANCE);
                    l_Statement->setUInt32(0, p_InstanceSave->GetInstanceId());
                    l_Statement->setBool(1, p_Permanent);
                    l_Statement->setUInt32(2, GetGUIDLow());
                    l_Statement->setUInt32(3, l_InstanceBind.save->GetInstanceId());
                    CharacterDatabase.Execute(l_Statement);
                }
            }
        }
        else
        {
            if (!p_Load)
            {
                PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_INSTANCE);
                l_Statement->setUInt32(0, GetGUIDLow());
                l_Statement->setUInt32(1, p_InstanceSave->GetInstanceId());
                l_Statement->setBool(2, p_Permanent);
                CharacterDatabase.Execute(l_Statement);
            }
        }

        if (l_InstanceBind.save != p_InstanceSave)
        {
            if (l_InstanceBind.save)
                l_InstanceBind.save->RemovePlayer(this);

            p_InstanceSave->AddPlayer(this);
        }

        if (p_Permanent)
            p_InstanceSave->SetCanReset(false);

        l_InstanceBind.save = p_InstanceSave;
        l_InstanceBind.perm = p_Permanent;

        if (!p_Load)
            sLog->outDebug(LOG_FILTER_MAPS, "Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d", GetName(), GetGUIDLow(), p_InstanceSave->GetMapId(), p_InstanceSave->GetInstanceId(), p_InstanceSave->GetDifficultyID());

        sScriptMgr->OnPlayerBindToInstance(this, p_InstanceSave->GetDifficultyID(), p_InstanceSave->GetMapId(), p_Permanent);
        return &l_InstanceBind;
    }
    else
        return nullptr;
}

void Player::BindToInstance()
{
    InstanceSave* mapSave = sInstanceSaveMgr->GetInstanceSave(_pendingBindId);
    if (!mapSave) //it seems sometimes mapSave is NULL, but I did not check why
        return;

    WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4);
    data.WriteBit(false);
    GetSession()->SendPacket(&data);
    BindToInstance(mapSave, true);

    GetSession()->SendCalendarRaidLockout(mapSave, true);
}

void Player::SendRaidInfo()
{
    uint32 l_Counter = 0;
    WorldPacket l_Data(SMSG_RAID_INSTANCE_INFO, 1024);
    ByteBuffer l_Buffer;
    time_t l_Now = time(NULL);

    for (uint8 l_Iter = 0; l_Iter < Difficulty::MaxDifficulties; ++l_Iter)
    {
        for (BoundInstancesMap::iterator l_Itr = m_boundInstances[l_Iter].begin(); l_Itr != m_boundInstances[l_Iter].end(); ++l_Itr)
        {
            if (l_Itr->second.perm)
            {
                InstanceSave* l_Save = l_Itr->second.save;
                l_Counter++;

                l_Buffer << uint32(l_Save->GetMapId());
                l_Buffer << uint32(l_Save->GetDifficultyID());
                l_Buffer << uint64(l_Save->GetInstanceId());
                l_Buffer << uint32(l_Save->GetResetTime() - l_Now);
                l_Buffer << uint32(l_Save->GetEncounterMask());
                l_Buffer.WriteBit(true);    ///< Locked
                l_Buffer.WriteBit(false);   ///< Extended
                l_Buffer.FlushBits();
            }
        }
    }

    l_Data << uint32(l_Counter);
    if (l_Counter)
        l_Data.append(l_Buffer);

    GetSession()->SendPacket(&l_Data);
}

/*
- called on every successful teleportation to a map
*/
void Player::SendSavedInstances()
{
    bool hasBeenSaved = false;
    WorldPacket data;

    for (uint8 i = 0; i < Difficulty::MaxDifficulties; ++i)
    {
        for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
        {
            if (itr->second.perm)                               // only permanent binds are sent
            {
                hasBeenSaved = true;
                break;
            }
        }
    }

    //Send opcode SMSG_UPDATE_INSTANCE_OWNERSHIP. true or false means, whether you have current raid/heroic instances
    data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP, 4);
    data << uint32(hasBeenSaved);
    GetSession()->SendPacket(&data);

    if (!hasBeenSaved)
        return;

    for (uint8 i = 0; i < Difficulty::MaxDifficulties; ++i)
    {
        for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
        {
            if (itr->second.perm)
            {
                data.Initialize(SMSG_UPDATE_LAST_INSTANCE, 4);
                data << uint32(itr->second.save->GetMapId());
                GetSession()->SendPacket(&data);
            }
        }
    }
}

/// convert the player's binds to the group
void Player::ConvertInstancesToGroup(Player* player, Group* group, bool switchLeader)
{
    // copy all binds to the group, when changing leader it's assumed the character
    // will not have any solo binds

    for (uint8 i = 0; i < Difficulty::MaxDifficulties; ++i)
    {
        for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
        {
            if (!switchLeader || !group->GetBoundInstance(itr->second.save->GetDifficultyID(), itr->first))
                group->BindToInstance(itr->second.save, itr->second.perm, false);

            // permanent binds are not removed
            if (switchLeader && !itr->second.perm)
            {
                // increments itr in call
                player->UnbindInstance(itr, Difficulty(i), false);
            }
            else
                ++itr;
        }
    }
}

bool Player::Satisfy(AccessRequirement const* ar, uint32 target_map, bool report)
{
    if (!isGameMaster() && ar)
    {
        uint8 LevelMin = 0;
        uint8 LevelMax = 0;

        MapEntry const* mapEntry = sMapStore.LookupEntry(target_map);
        if (!mapEntry)
            return false;

        if (!sWorld->getBoolConfig(CONFIG_INSTANCE_IGNORE_LEVEL))
        {
            if (ar->levelMin && getLevel() < ar->levelMin)
                LevelMin = ar->levelMin;
            if (ar->levelMax && getLevel() > ar->levelMax)
                LevelMax = ar->levelMax;
        }

        uint32 missingItem = 0;
        if (ar->item)
        {
            if (!HasItemCount(ar->item) &&
                (!ar->item2 || !HasItemCount(ar->item2)))
                missingItem = ar->item;
        }
        else if (ar->item2 && !HasItemCount(ar->item2))
            missingItem = ar->item2;

        if (DisableMgr::IsDisabledFor(DISABLE_TYPE_MAP, target_map, this))
            return false;

        uint32 missingQuest = 0;
        if (GetTeam() == ALLIANCE && ar->quest_A && !GetQuestRewardStatus(ar->quest_A))
            missingQuest = ar->quest_A;
        else if (GetTeam() == HORDE && ar->quest_H && !GetQuestRewardStatus(ar->quest_H))
            missingQuest = ar->quest_H;

        uint32 missingAchievement = 0;
        Player* leader = this;
        uint64 leaderGuid = GetGroup() ? GetGroup()->GetLeaderGUID() : GetGUID();
        if (leaderGuid != GetGUID())
            leader = ObjectAccessor::FindPlayer(leaderGuid);

        if (ar->achievement)
            if (!leader || !leader->GetAchievementMgr().HasAchieved(ar->achievement))
                missingAchievement = ar->achievement;

        uint32 missingLeaderAchievement = 0;
        if (ar->leader_achievement)
        {
            if (GetGroup())
            {
                if (Player* pLeader = ObjectAccessor::FindPlayer(GetGroup()->GetLeaderGUID()))
                    if (!pLeader->GetAchievementMgr().HasAchieved(ar->leader_achievement))
                        missingLeaderAchievement = ar->leader_achievement;
            }
            else
                if (!GetAchievementMgr().HasAchieved(ar->leader_achievement))
                    missingLeaderAchievement = ar->leader_achievement;
        }

        Difficulty target_difficulty = GetDifficultyID(mapEntry);
        MapDifficulty const* mapDiff = GetDownscaledMapDifficultyData(target_map, target_difficulty);
        if (!mapDiff)
            return false;

        if (LevelMin || LevelMax || missingItem || missingQuest || missingAchievement || missingLeaderAchievement)
        {
            if (report)
            {
                if (missingQuest && !ar->questFailedText.empty())
                    ChatHandler(GetSession()).PSendSysMessage("%s", ar->questFailedText.c_str());
                else if (mapDiff->HasErrorMessage) // if (missingAchievement) covered by this case
                    SendTransferAborted(target_map, TRANSFER_ABORT_DIFFICULTY, target_difficulty);
            }
            return false;
        }
    }
    return true;
}

bool Player::CheckInstanceLoginValid()
{
    if (!GetMap())
        return false;

    if (!GetMap()->IsDungeon() || isGameMaster() || (GetMap()->IsDungeon() && GetMap()->Expansion() < 4))
        return true;

    if (GetMap()->IsRaid())
    {
        // cannot be in raid instance without a group
        if (!GetGroup())
            return false;
    }
    else
    {
        // cannot be in normal instance without a group and more players than 1 in instance
        if (!GetGroup() && GetMap()->GetPlayersCountExceptGMs() > 1)
            return false;
    }

    // do checks for satisfy accessreqs, instance full, encounter in progress (raid), perm bind group != perm bind player
    return sMapMgr->CanPlayerEnter(GetMap()->GetId(), this, true);
}

bool Player::_LoadHomeBind(PreparedQueryResult result)
{
    PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
    if (!info)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player (Name %s) has incorrect race/class (%u/%u) pair. Can't be loaded.", GetName(), uint32(getRace()), uint32(getClass()));
        return false;
    }

    bool ok = false;
    // SELECT mapId, zoneId, posX, posY, posZ FROM character_homebind WHERE guid = ?
    if (result)
    {
        Field* fields = result->Fetch();

        m_homebindMapId = fields[0].GetUInt16();
        m_homebindAreaId = fields[1].GetUInt16();
        m_homebindX = fields[2].GetFloat();
        m_homebindY = fields[3].GetFloat();
        m_homebindZ = fields[4].GetFloat();

        MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);

        // accept saved data only for valid position (and non instanceable), and accessable
        if (MapManager::IsValidMapCoord(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ) &&
            !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
            ok = true;
        else
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_HOMEBIND);
            stmt->setUInt32(0, GetGUIDLow());
            CharacterDatabase.Execute(stmt);
        }
    }

    if (!ok)
    {
        m_homebindMapId = info->mapId;
        m_homebindAreaId = info->areaId;
        m_homebindX = info->positionX;
        m_homebindY = info->positionY;
        m_homebindZ = info->positionZ;

        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_HOMEBIND);
        stmt->setUInt32(0, GetGUIDLow());
        stmt->setUInt16(1, m_homebindMapId);
        stmt->setUInt16(2, m_homebindAreaId);
        stmt->setFloat (3, m_homebindX);
        stmt->setFloat (4, m_homebindY);
        stmt->setFloat (5, m_homebindZ);
        CharacterDatabase.Execute(stmt);
    }

    sLog->outDebug(LOG_FILTER_PLAYER, "Setting player home position - mapid: %u, areaid: %u, X: %f, Y: %f, Z: %f",
        m_homebindMapId, m_homebindAreaId, m_homebindX, m_homebindY, m_homebindZ);

    return true;
}

/*********************************************************/
/***                   SAVE SYSTEM                     ***/
/*********************************************************/
void Player::SaveToDB(bool create /*=false*/)
{
    // delay auto save at any saves (manual, in code, or autosave)
    m_nextSave = sWorld->getIntConfig(CONFIG_INTERVAL_SAVE);

    //lets allow only players in world to be saved
    if (IsBeingTeleportedFar())
    {
        ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
        return;
    }

    // first save/honor gain after midnight will also update the player's honor fields
    UpdateHonorFields();

    sLog->outDebug(LOG_FILTER_UNITS, "The value of player %s at save: ", m_name.c_str());
    outDebugValues();

    PreparedStatement* stmt = NULL;
    uint8 index = 0;

    if (create)
    {
        //! Insert query
        //! TO DO: Filter out more redundant fields that can take their default value at player create
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER);
        stmt->setUInt32(index++, GetGUIDLow());
        stmt->setUInt32(index++, GetSession()->GetAccountId());
        stmt->setString(index++, GetName());
        stmt->setUInt8(index++, getRace());
        stmt->setUInt8(index++, getClass());
        stmt->setUInt8(index++, getGender());
        stmt->setUInt8(index++, getLevel());
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_XP));
        stmt->setUInt64(index++, GetMoney());
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_HAIR_COLOR_ID));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_REST_STATE));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_PLAYER_FLAGS));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_PLAYER_FLAGS_EX));
        stmt->setUInt16(index++, (uint16)GetMapId());
        stmt->setUInt32(index++, (uint32)GetInstanceId());
        stmt->setUInt8(index++, GetDungeonDifficultyID());
        stmt->setUInt8(index++, GetRaidDifficultyID());
        stmt->setUInt8(index++, GetLegacyRaidDifficultyID());
        stmt->setFloat(index++, finiteAlways(GetPositionX()));
        stmt->setFloat(index++, finiteAlways(GetPositionY()));
        stmt->setFloat(index++, finiteAlways(GetPositionZ()));
        stmt->setFloat(index++, finiteAlways(GetOrientation()));

        std::ostringstream ss;
        ss << m_taxi;
        stmt->setString(index++, ss.str());
        stmt->setUInt8(index++, m_cinematic);
        stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]);
        stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]);
        stmt->setFloat(index++, finiteAlways(m_rest_bonus));
        stmt->setUInt32(index++, uint32(time(NULL)));
        stmt->setUInt8(index++,  (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0));
        //save, far from tavern/city
        //save, but in tavern/city
        stmt->setUInt32(index++, GetTalentResetCost());
        stmt->setUInt32(index++, GetTalentResetTime());

        ss.str("");
        for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
            ss << GetPrimaryTalentTree(i) << " ";
        stmt->setString(index++, ss.str());
        stmt->setUInt16(index++, (uint16)m_ExtraFlags);
        stmt->setUInt8(index++,  m_stableSlots);
        stmt->setUInt16(index++, (uint16)m_atLoginFlags);
        stmt->setUInt16(index++, GetZoneId(true));
        stmt->setUInt32(index++, uint32(m_deathExpireTime));

        ss.str("");
        ss << m_taxi.SaveTaxiDestinationsToString();

        stmt->setString(index++, ss.str());
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS));
        stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 0));
        stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 1));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_PLAYER_TITLE));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX));
        stmt->setUInt8(index++, GetDrunkValue());
        stmt->setUInt32(index++, GetHealth());

        uint32 storedPowers = 0;
        for (uint32 i = 0; i < MAX_POWERS; ++i)
        {
            if (GetPowerIndex(Powers(i), getClass()) != MAX_POWERS)
            {
                stmt->setUInt32(index++, GetUInt32Value(UNIT_FIELD_POWER + storedPowers));
                if (++storedPowers >= MAX_POWERS_PER_CLASS)
                    break;
            }
        }

        for (; storedPowers < MAX_POWERS_PER_CLASS; ++storedPowers)
            stmt->setUInt32(index++, 0);

        stmt->setUInt32(index++, GetSession()->GetLatency());

        stmt->setUInt8(index++, GetSpecsCount());
        stmt->setUInt8(index++, GetActiveSpec());

        stmt->setUInt32(index++, 0);
        stmt->setUInt32(index++, 0);

        ss.str("");
        for (uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i)
            ss << GetUInt32Value(PLAYER_FIELD_EXPLORED_ZONES + i) << ' ';
        stmt->setString(index++, ss.str());

        ss.str("");
        // cache equipment...
        for (uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i)
        {
            uint64 l_Value = 0;
            ((uint32*)(&l_Value))[0] = GetUInt32Value(PLAYER_FIELD_VISIBLE_ITEMS + i + 0);
            ((uint32*)(&l_Value))[1] = GetItemDisplayID(((uint32*)(&l_Value))[0], (uint32)GetUInt16Value(PLAYER_FIELD_VISIBLE_ITEMS + i + 1, 0));

            ss << l_Value << ' ';

            if (((i + 1) % 2) == 0)
                ss << ' ';
        }

        // ...and bags for enum opcode
        for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
        {
            if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                ss << item->GetEntry();
            else
                ss << '0';

            ss << " 0";
            ss << " 0 ";
        }
        stmt->setString(index++, ss.str());

        ss.str("");
        for (uint32 i = 0; i < KNOWN_TITLES_SIZE; ++i)
            ss << GetUInt32Value(PLAYER_FIELD_KNOWN_TITLES + i) << ' ';
        stmt->setString(index++, ss.str());

        stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_LIFETIME_MAX_RANK, 1));
        stmt->setUInt8(index++, m_currentPetSlot);
        stmt->setUInt32(index++, m_grantableLevels);
        stmt->setUInt32(index++, m_LastSummonedBattlePet);
        stmt->setFloat(index++, m_PersonnalXpRate);
        stmt->setUInt32(index++, m_petSlotUsed);
    }
    else
    {
        // Update query
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER);
        stmt->setString(index++, GetName());
        stmt->setUInt8(index++, getRace());
        stmt->setUInt8(index++, getClass());
        stmt->setUInt8(index++, getGender());
        stmt->setUInt8(index++, getLevel());
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_XP));
        stmt->setUInt64(index++, GetMoney());
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_HAIR_COLOR_ID));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_REST_STATE));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_PLAYER_FLAGS));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_PLAYER_FLAGS_EX));

        uint16 l_MapID = IsInGarrison() ? MS::Garrison::Globals::BaseMap : (IsBeingTeleported() ? GetTeleportDest().GetMapId() : GetMapId());

        if (!IsBeingTeleported())
        {
            stmt->setUInt16(index++, (uint16)l_MapID);
            stmt->setUInt32(index++, (uint32)GetInstanceId());
            stmt->setUInt8(index++, GetDungeonDifficultyID());
            stmt->setUInt8(index++, GetRaidDifficultyID());
            stmt->setUInt8(index++, GetLegacyRaidDifficultyID());
            stmt->setFloat(index++, finiteAlways(GetPositionX()));
            stmt->setFloat(index++, finiteAlways(GetPositionY()));
            stmt->setFloat(index++, finiteAlways(GetPositionZ()));
            stmt->setFloat(index++, finiteAlways(GetOrientation()));
        }
        else
        {
            stmt->setUInt16(index++, (uint16)GetTeleportDest().GetMapId());
            stmt->setUInt32(index++, (uint32)0);
            stmt->setUInt8(index++, GetDungeonDifficultyID());
            stmt->setUInt8(index++, GetRaidDifficultyID());
            stmt->setUInt8(index++, GetLegacyRaidDifficultyID());
            stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetPositionX()));
            stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetPositionY()));
            stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetPositionZ()));
            stmt->setFloat(index++, finiteAlways(GetTeleportDest().GetOrientation()));
        }

        std::ostringstream ss;
        ss << m_taxi;
        stmt->setString(index++, ss.str());
        stmt->setUInt8(index++, m_cinematic);
        stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_TOTAL]);
        stmt->setUInt32(index++, m_Played_time[PLAYED_TIME_LEVEL]);
        stmt->setFloat(index++, finiteAlways(m_rest_bonus));
        stmt->setUInt32(index++, uint32(time(NULL)));
        stmt->setUInt8(index++,  (HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0));
        //save, far from tavern/city
        //save, but in tavern/city
        stmt->setUInt32(index++, GetTalentResetCost());
        stmt->setUInt32(index++, GetTalentResetTime());

        ss.str("");
        for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
            ss << GetPrimaryTalentTree(i) << " ";
        stmt->setString(index++, ss.str());
        stmt->setUInt16(index++, (uint16)m_ExtraFlags);
        stmt->setUInt8(index++,  m_stableSlots);
        stmt->setUInt16(index++, (uint16)m_atLoginFlags);
        stmt->setUInt16(index++, GetZoneId(true));
        stmt->setUInt32(index++, uint32(m_deathExpireTime));

        ss.str("");
        ss << m_taxi.SaveTaxiDestinationsToString();

        stmt->setString(index++, ss.str());
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS));
        stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 0));
        stmt->setUInt16(index++, GetUInt16Value(PLAYER_FIELD_YESTERDAY_HONORABLE_KILLS, 1));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_PLAYER_TITLE));
        stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX));
        stmt->setUInt8(index++, GetDrunkValue());
        stmt->setUInt32(index++, GetHealth());

        uint32 storedPowers = 0;
        for (uint32 i = 0; i < MAX_POWERS; ++i)
        {
            if (GetPowerIndex(Powers(i), getClass()) != MAX_POWERS)
            {
                stmt->setUInt32(index++, GetUInt32Value(UNIT_FIELD_POWER + storedPowers));
                if (++storedPowers >= MAX_POWERS_PER_CLASS)
                    break;
            }
        }

        for (; storedPowers < MAX_POWERS_PER_CLASS; ++storedPowers)
            stmt->setUInt32(index++, 0);

        stmt->setUInt32(index++, GetSession()->GetLatency());

        stmt->setUInt8(index++, GetSpecsCount());
        stmt->setUInt8(index++, GetActiveSpec());

        stmt->setUInt32(index++, GetSpecializationId(0));
        stmt->setUInt32(index++, GetSpecializationId(1));

        ss.str("");
        for (uint32 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i)
            ss << GetUInt32Value(PLAYER_FIELD_EXPLORED_ZONES + i) << ' ';
        stmt->setString(index++, ss.str());

        ss.str("");

        // cache equipment...
        for (uint32 i = 0; i < EQUIPMENT_SLOT_END * 2; ++i)
        {
            uint64 l_Value = 0;
            ((uint32*)(&l_Value))[0] = GetUInt32Value(PLAYER_FIELD_VISIBLE_ITEMS + i + 0);
            ((uint32*)(&l_Value))[1] = GetItemDisplayID(((uint32*)(&l_Value))[0], (uint32)GetUInt16Value(PLAYER_FIELD_VISIBLE_ITEMS + i + 1, 0));

            ss << l_Value << ' ';

            if (((i + 1) % 2) == 0)
                ss << ' ';
        }

        // ...and bags for enum opcode
        for (uint32 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
        {
            if (Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
                ss << item->GetEntry();
            else
                ss << '0';
            ss << " 0";
            ss << " 0 ";
        }

        stmt->setString(index++, ss.str());

        ss.str("");
        for (uint32 i = 0; i < KNOWN_TITLES_SIZE; ++i)
            ss << GetUInt32Value(PLAYER_FIELD_KNOWN_TITLES + i) << ' ';

        stmt->setString(index++, ss.str());
        stmt->setUInt8(index++, GetByteValue(PLAYER_FIELD_LIFETIME_MAX_RANK, 1));
        stmt->setUInt8(index++, m_currentPetSlot);
        stmt->setUInt32(index++, m_grantableLevels);

        stmt->setUInt8(index++, IsInWorld() ? 1 : 0);

        stmt->setUInt32(index++, GetSpecializationResetCost());
        stmt->setUInt32(index++, GetSpecializationResetTime());
        stmt->setUInt32(index++, m_LastSummonedBattlePet);

        stmt->setFloat(index++, m_PersonnalXpRate);

        // Index
        stmt->setUInt32(index++, GetGUIDLow());
        stmt->setUInt32(index++, m_petSlotUsed);
    }

    SQLTransaction trans = CharacterDatabase.BeginTransaction();
    SQLTransaction accountTrans = LoginDatabase.BeginTransaction();

    trans->Append(stmt);

    if (m_Garrison)
        m_Garrison->Save();

    if (m_mailsUpdated)                                     //save mails only when needed
        _SaveMail(trans);

    _SaveArenaData(trans);
    _SaveBGData(trans);
    _SaveInventory(trans);
    _SaveVoidStorage(trans);
    _SaveQuestStatus(trans);
    _SaveQuestObjectiveStatus(trans);
    _SaveDailyQuestStatus(trans);
    _SaveWeeklyQuestStatus(trans);
    _SaveSeasonalQuestStatus(trans);
    _SaveMonthlyQuestStatus(trans);
    _SaveTalents(trans);
    _SaveSpells(trans, accountTrans);
    _SaveSpellCooldowns(trans);
    _SaveChargesCooldowns(trans);
    _SaveActions(trans);
    _SaveAuras(trans);
    _SaveSkills(trans);
    m_achievementMgr.SaveToDB(trans);
    m_reputationMgr.SaveToDB(trans);
    _SaveEquipmentSets(trans);
    GetSession()->SaveTutorialsData(trans);                 // changed only while character in game
    _SaveGlyphs(trans);
    _SaveInstanceTimeRestrictions(trans);
    _SaveCurrency(trans);
    m_archaeologyMgr.SaveArchaeology(trans);
    _SaveCharacterWorldStates(trans);
    _SaveCharacterGarrisonTavernDatas(trans);

    // check if stats should only be saved on logout
    // save stats can be out of transaction
    if (m_session->isLogingOut() || !sWorld->getBoolConfig(CONFIG_STATS_SAVE_ONLY_ON_LOGOUT))
        _SaveStats(trans);

    MS::Utilities::CallBackPtr l_CharCreateCallback = nullptr;
    if (create)
    {
        uint32 l_AccountID = m_session->GetAccountId();
        l_CharCreateCallback = std::make_shared<MS::Utilities::Callback>([l_AccountID](bool p_Success) -> void
        {
            WorldSession* l_Session = sWorld->FindSession(l_AccountID);
            if (l_Session == nullptr)
                return;

            WorldPacket l_Data(SMSG_CREATE_CHAR, 1);
            l_Data << uint8(p_Success ? CHAR_CREATE_SUCCESS : CHAR_CREATE_ERROR);
            l_Session->SendPacket(&l_Data);
        });
    }

    for (std::vector<BattlePet::Ptr>::iterator l_It = m_BattlePets.begin(); l_It != m_BattlePets.end(); ++l_It)
    {
        BattlePet::Ptr l_Pet = (*l_It);
        l_Pet->Save(accountTrans);
    }

    CharacterDatabase.CommitTransaction(trans, l_CharCreateCallback);
    LoginDatabase.CommitTransaction(accountTrans);

    // we save the data here to prevent spamming
    sAnticheatMgr->SavePlayerData(this);

    // save pet (hunter pet level and experience and all type pets health/mana).
    if (Pet* pet = GetPet())
        pet->SavePetToDB(PET_SLOT_ACTUAL_PET_SLOT, pet->m_Stampeded);
}

// fast save function for item/money cheating preventing - save only inventory and money state
void Player::SaveInventoryAndGoldToDB(SQLTransaction& trans)
{
    _SaveInventory(trans);
    _SaveCurrency(trans);
    _SaveVoidStorage(trans);
    SaveGoldToDB(trans);
}

void Player::SaveGoldToDB(SQLTransaction& trans)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_MONEY);
    stmt->setUInt64(0, GetMoney());
    stmt->setUInt32(1, GetGUIDLow());
    trans->Append(stmt);
}

void Player::_SaveActions(SQLTransaction& trans)
{
    PreparedStatement* stmt = NULL;

    for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end();)
    {
        switch (itr->second.uState)
        {
            case ACTIONBUTTON_NEW:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_ACTION);
                stmt->setUInt32(0, GetGUIDLow());
                stmt->setUInt8(1, GetActiveSpec());
                stmt->setUInt8(2, itr->first);
                stmt->setUInt32(3, itr->second.GetAction());
                stmt->setUInt8(4, uint8(itr->second.GetType()));
                trans->Append(stmt);

                itr->second.uState = ACTIONBUTTON_UNCHANGED;
                ++itr;
                break;
            case ACTIONBUTTON_CHANGED:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHAR_ACTION);
                stmt->setUInt32(0, itr->second.GetAction());
                stmt->setUInt8(1, uint8(itr->second.GetType()));
                stmt->setUInt32(2,  GetGUIDLow());
                stmt->setUInt8(3, itr->first);
                stmt->setUInt8(4, GetActiveSpec());
                trans->Append(stmt);

                itr->second.uState = ACTIONBUTTON_UNCHANGED;
                ++itr;
                break;
            case ACTIONBUTTON_DELETED:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION_BY_BUTTON_SPEC);
                stmt->setUInt32(0, GetGUIDLow());
                stmt->setUInt8(1, itr->first);
                stmt->setUInt8(2, GetActiveSpec());
                trans->Append(stmt);

                m_actionButtons.erase(itr++);
                break;
            default:
                ++itr;
                break;
        }
    }
}

void Player::_SaveAuras(SQLTransaction& trans)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);
    stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_AURA_EFFECT);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);

    for (AuraMap::const_iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end(); ++itr)
    {
        if (!itr->second->CanBeSaved())
            continue;

        Aura* aura = itr->second;
        AuraApplication * foundAura = GetAuraApplication(aura->GetId(), aura->GetCasterGUID(), aura->GetCastItemGUID());

        if (!foundAura)
            continue;


        uint8 index = 0;
        int32 damage[SpellEffIndex::MAX_EFFECTS];
        int32 baseDamage[SpellEffIndex::MAX_EFFECTS];
        uint32 effMask = 0;
        uint32 recalculateMask = 0;
        for (uint8 i = 0; i < aura->GetEffectCount(); ++i)
        {
            if (AuraEffect const* effect = aura->GetEffect(i))
            {
                index = 0;
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_AURA_EFFECT);
                stmt->setUInt32(index++, GetGUIDLow());
                stmt->setUInt8(index++, foundAura->GetSlot());
                stmt->setUInt8(index++, i);
                stmt->setInt32(index++, effect->GetBaseAmount());
                stmt->setInt32(index++, effect->GetAmount());

                trans->Append(stmt);

                baseDamage[i] = effect->GetBaseAmount();
                damage[i] = effect->GetAmount();
                effMask |= 1 << i;
                if (effect->CanBeRecalculated())
                    recalculateMask |= 1 << i;
            }
            else
            {
                baseDamage[i] = 0;<--- Variable 'baseDamage' is assigned a value that is never used.
                damage[i] = 0;<--- Variable 'damage' is assigned a value that is never used.
            }
        }

        index = 0;
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_AURA);
        stmt->setUInt32(index++, GetGUIDLow());
        stmt->setUInt8(index++, foundAura->GetSlot());
        stmt->setUInt64(index++, itr->second->GetCasterGUID());
        stmt->setUInt64(index++, itr->second->GetCastItemGUID());
        stmt->setUInt32(index++, itr->second->GetId());
        stmt->setUInt8(index++, effMask);
        stmt->setUInt8(index++, recalculateMask);
        stmt->setUInt8(index++, itr->second->GetStackAmount());
        stmt->setInt32(index++, itr->second->GetMaxDuration());
        stmt->setInt32(index++, itr->second->GetDuration());
        stmt->setUInt8(index, itr->second->GetCharges());
        trans->Append(stmt);
    }
}

void Player::_SaveInventory(SQLTransaction& trans)
{
    // force items in buyback slots to new state
    // and remove those that aren't already
    for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
    {
        Item* item = m_items[i];
        if (!item || item->GetState() == ITEM_NEW)
            continue;

        trans->PAppend("DELETE FROM character_inventory WHERE item = %u", item->GetGUIDLow());
        trans->PAppend("DELETE FROM item_instance WHERE guid = %u", item->GetGUIDLow());

        m_items[i]->FSetState(ITEM_NEW);
    }

    // Updated played time for refundable items. We don't do this in Player::Update because there's simply no need for it,
    // the client auto counts down in real time after having received the initial played time on the first
    // SMSG_SET_ITEM_PURCHASE_DATA packet.
    // Item::UpdatePlayedTime is only called when needed, which is in DB saves, and item refund info requests.
    std::set<uint32>::iterator i_next;
    for (std::set<uint32>::iterator itr = m_refundableItems.begin(); itr!= m_refundableItems.end(); itr = i_next)
    {
        // use copy iterator because itr may be invalid after operations in this loop
        i_next = itr;
        ++i_next;

        Item* iPtr = GetItemByGuid(MAKE_NEW_GUID(*itr, 0, HIGHGUID_ITEM));
        if (iPtr)
        {
            iPtr->UpdatePlayedTime(this);
            continue;
        }
        else
        {
            sLog->outError(LOG_FILTER_PLAYER, "Can't find item guid %u but is in refundable storage for player %u ! Removing.", *itr, GetGUIDLow());
            m_refundableItems.erase(itr);
        }
    }

    // update enchantment durations
    for (EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
        itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration, this);

    // if no changes
    if (m_itemUpdateQueue.empty())
        return;

    uint32 lowGuid = GetGUIDLow();
    for (size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
    {
        Item* item = m_itemUpdateQueue[i];
        if (!item)
            continue;

        Bag* container = item->GetContainer();
        uint32 bag_guid = container ? container->GetGUIDLow() : 0;

        if (item->GetState() != ITEM_REMOVED)
        {
            Item* test = GetItemByPos(item->GetBagSlot(), item->GetSlot());
            if (test == NULL)
            {
                uint32 bagTestGUID = 0;
                if (Item* test2 = GetItemByPos(INVENTORY_SLOT_BAG_0, item->GetBagSlot()))
                    bagTestGUID = test2->GetGUIDLow();
                sLog->outError(LOG_FILTER_PLAYER, "Player(GUID: %u Name: %s)::_SaveInventory - the bag(%u) and slot(%u) values for the item with guid %u (state %d) are incorrect, the player doesn't have an item at that position!", lowGuid, GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), (int32)item->GetState());
                // according to the test that was just performed nothing should be in this slot, delete

                trans->PAppend("DELETE FROM character_inventory WHERE bag=%u AND slot=%u AND guid=%u", bagTestGUID, item->GetSlot(), lowGuid);

                // also THIS item should be somewhere else, cheat attempt
                item->FSetState(ITEM_REMOVED); // we are IN updateQueue right now, can't use SetState which modifies the queue
                DeleteRefundReference(item->GetGUIDLow());
                // don't skip, let the switch delete it
                //continue;
            }
            else if (test != item)
            {
                sLog->outError(LOG_FILTER_PLAYER, "Player(GUID: %u Name: %s)::_SaveInventory - the bag(%u) and slot(%u) values for the item with guid %u are incorrect, the item with guid %u is there instead!", lowGuid, GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
                // save all changes to the item...
                if (item->GetState() != ITEM_NEW) // only for existing items, no dupes
                    item->SaveToDB(trans);
                // ...but do not save position in inventory
                continue;
            }
        }

        switch (item->GetState())
        {
            case ITEM_NEW:
            case ITEM_CHANGED:
                trans->PAppend("REPLACE INTO character_inventory (guid, bag, slot, item) VALUES ('%u', '%u', '%u', '%u')", lowGuid, bag_guid, item->GetSlot(), item->GetGUIDLow());
                break;
            case ITEM_REMOVED:
                trans->PAppend("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
                break;
            case ITEM_UNCHANGED:
                break;
        }

        item->SaveToDB(trans);                                   // item have unchanged inventory record and can be save standalone
    }
    m_itemUpdateQueue.clear();
}

void Player::_SaveVoidStorage(SQLTransaction& trans)
{
    if (!m_VoidStorageLoaded)
        return;

    PreparedStatement* stmt = NULL;
    uint32 lowGuid = GetGUIDLow();

    for (uint8 i = 0; i < VOID_STORAGE_MAX_SLOT; ++i)
    {
        if (!_voidStorageItems[i]) // unused item
        {
            // DELETE FROM void_storage WHERE slot = ? AND playerGuid = ?
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_VOID_STORAGE_ITEM_BY_SLOT);
            stmt->setUInt8(0, i);
            stmt->setUInt32(1, lowGuid);
        }
        else
        {
            // REPLACE INTO character_inventory (itemId, playerGuid, itemEntry, slot, creatorGuid) VALUES (?, ?, ?, ?, ?)
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_VOID_STORAGE_ITEM);
            stmt->setUInt64(0, _voidStorageItems[i]->ItemId);
            stmt->setUInt32(1, lowGuid);
            stmt->setUInt32(2, _voidStorageItems[i]->ItemEntry);
            stmt->setUInt8(3, i);
            stmt->setUInt32(4, _voidStorageItems[i]->CreatorGuid);
            stmt->setUInt32(5, _voidStorageItems[i]->ItemRandomPropertyId);
            stmt->setUInt32(6, _voidStorageItems[i]->ItemSuffixFactor);

            std::ostringstream l_Bonuses;

            for (uint32 l_I = 0; l_I < _voidStorageItems[i]->Bonuses.size(); l_I++)
            {
                if (_voidStorageItems[i])
                    l_Bonuses << _voidStorageItems[i]->Bonuses[l_I] << ' ';
            }

            stmt->setString(7, l_Bonuses.str());

        }

        trans->Append(stmt);
    }
}

void Player::_SaveMail(SQLTransaction& trans)
{
    PreparedStatement* stmt = NULL;

    for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
    {
        Mail* m = (*itr);
        if (m->state == MAIL_STATE_CHANGED)
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_MAIL);
            stmt->setUInt8(0, uint8(m->HasItems() ? 1 : 0));
            stmt->setUInt32(1, uint32(m->expire_time));
            stmt->setUInt32(2, uint32(m->deliver_time));
            stmt->setUInt64(3, m->money);
            stmt->setUInt64(4, m->COD);
            stmt->setUInt8(5, uint8(m->checked));
            stmt->setUInt32(6, m->messageID);

            trans->Append(stmt);

            if (!m->removedItems.empty())
            {
                for (std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
                {
                    stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM);
                    stmt->setUInt32(0, *itr2);
                    trans->Append(stmt);
                }
                m->removedItems.clear();
            }
            m->state = MAIL_STATE_UNCHANGED;
        }
        else if (m->state == MAIL_STATE_DELETED)
        {
            if (m->HasItems())
            {
                PreparedStatement* stmt = NULL;
                for (MailItemInfoVec::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
                {
                    stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE);
                    stmt->setUInt32(0, itr2->item_guid);
                    trans->Append(stmt);
                }
            }
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_BY_ID);
            stmt->setUInt32(0, m->messageID);
            trans->Append(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_MAIL_ITEM_BY_ID);
            stmt->setUInt32(0, m->messageID);
            trans->Append(stmt);
        }
    }

    //deallocate deleted mails...
    for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();)
    {
        if ((*itr)->state == MAIL_STATE_DELETED)
        {
            Mail* m = *itr;
            m_mail.erase(itr);
            delete m;
            itr = m_mail.begin();
        }
        else
            ++itr;
    }

    m_mailsUpdated = false;
}

void Player::_SaveQuestStatus(SQLTransaction& trans)
{
    bool isTransaction = trans.get() != nullptr;
    if (!isTransaction)
        trans = CharacterDatabase.BeginTransaction();

    QuestStatusSaveMap::iterator saveItr;
    QuestStatusMap::iterator statusItr;
    PreparedStatement* stmt = NULL;

    bool keepAbandoned = !(sWorld->GetCleaningFlags() & CharacterDatabaseCleaner::CLEANING_FLAG_QUESTSTATUS);

    for (saveItr = m_QuestStatusSave.begin(); saveItr != m_QuestStatusSave.end(); ++saveItr)
    {
        if (saveItr->second)
        {
            statusItr = m_QuestStatus.find(saveItr->first);
            if (statusItr != m_QuestStatus.end() && (keepAbandoned || statusItr->second.Status != QUEST_STATUS_NONE))
            {
                uint8 index = 0;
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_QUESTSTATUS);

                stmt->setUInt32(index++, GetGUIDLow());
                stmt->setUInt32(index++, statusItr->first);
                stmt->setUInt8(index++, uint8(statusItr->second.Status));
                stmt->setBool(index++, statusItr->second.Explored);
                stmt->setUInt32(index++, uint32(statusItr->second.Timer / IN_MILLISECONDS+ sWorld->GetGameTime()));

                trans->Append(stmt);
            }
        }
        else
        {
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_BY_QUEST);
            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt32(1, saveItr->first);
            trans->Append(stmt);
        }
    }

    for (saveItr = m_RewardedQuestsSave.begin(); saveItr != m_RewardedQuestsSave.end(); ++saveItr)
    {
        if (saveItr->second)
        {
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_QUESTSTATUS);
            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt32(1, saveItr->first);
            trans->Append(stmt);

        }
        else if (!keepAbandoned)
        {
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_REWARDED_BY_QUEST);
            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt32(1, saveItr->first);
            trans->Append(stmt);
        }
    }

    m_RewardedQuestsSave.clear();

    if (!isTransaction)
        CharacterDatabase.CommitTransaction(trans);
}

void Player::_SaveQuestObjectiveStatus(SQLTransaction& trans)
{
    for (QuestObjectiveStatusMap::const_iterator citr = m_questObjectiveStatus.begin(); citr != m_questObjectiveStatus.end(); ++citr)
    {
        uint32 questId = sObjectMgr->GetQuestObjectiveQuestId(citr->first);
        if (!questId)
            continue;

        QuestStatusSaveMap::const_iterator citrSave = m_QuestStatusSave.find(questId);
        if (citrSave == m_QuestStatusSave.end())
            continue;

        if (citrSave->second)
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_REP_CHAR_QUESTSTATUS_OBJECTIVE);
            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt32(1, citr->first);
            stmt->setUInt32(2, citr->second);
            trans->Append(stmt);
        }
        else
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_QUESTSTATUS_OBJECTIVE);
            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt32(1, citr->first);
            trans->Append(stmt);
        }
    }

    m_QuestStatusSave.clear();
}

void Player::_SaveDailyQuestStatus(SQLTransaction& trans)
{
    if (!m_DailyQuestChanged)
        return;

    m_DailyQuestChanged = false;

    // save last daily quest time for all quests: we need only mostly reset time for reset check anyway

    // we don't need transactions here.
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_DAILY_CHAR);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);

    for (auto id : m_dailyQuestStorage)
    {
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS);
        stmt->setUInt32(0, GetGUIDLow());
        stmt->setUInt32(1, id);
        stmt->setUInt64(2, uint64(m_lastDailyQuestTime));
        trans->Append(stmt);
    }

    if (!m_DFQuests.empty())
    {
        for (DFQuestsDoneList::iterator itr = m_DFQuests.begin(); itr != m_DFQuests.end(); ++itr)
        {
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_DAILYQUESTSTATUS);
            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt32(1, (*itr));
            stmt->setUInt64(2, uint64(m_lastDailyQuestTime));
            trans->Append(stmt);
        }
    }
}

void Player::_SaveWeeklyQuestStatus(SQLTransaction& trans)
{
    if (!m_WeeklyQuestChanged || m_weeklyquests.empty())
        return;

    // we don't need transactions here.
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_WEEKLY_CHAR);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);

    for (QuestSet::const_iterator iter = m_weeklyquests.begin(); iter != m_weeklyquests.end(); ++iter)
    {
        uint32 quest_id  = *iter;

        stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_WEEKLYQUESTSTATUS);
        stmt->setUInt32(0, GetGUIDLow());
        stmt->setUInt32(1, quest_id);
        trans->Append(stmt);
    }

    m_WeeklyQuestChanged = false;
}

void Player::_SaveSeasonalQuestStatus(SQLTransaction& trans)
{
    if (!m_SeasonalQuestChanged || m_seasonalquests.empty())
        return;

    // we don't need transactions here.
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_SEASONAL_CHAR);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);

    for (SeasonalEventQuestMap::const_iterator iter = m_seasonalquests.begin(); iter != m_seasonalquests.end(); ++iter)
    {
        uint16 event_id = iter->first;
        for (SeasonalQuestSet::const_iterator itr = iter->second.begin(); itr != iter->second.end(); ++itr)
        {
            uint32 quest_id = (*itr);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_SEASONALQUESTSTATUS);
            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt32(1, quest_id);
            stmt->setUInt32(2, event_id);
            trans->Append(stmt);
        }
    }

    m_SeasonalQuestChanged = false;
}

void Player::_SaveMonthlyQuestStatus(SQLTransaction& trans)
{
    if (!m_MonthlyQuestChanged || m_monthlyquests.empty())
        return;

    // we don't need transactions here.
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_QUEST_STATUS_MONTHLY_CHAR);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);

    for (QuestSet::const_iterator iter = m_monthlyquests.begin(); iter != m_monthlyquests.end(); ++iter)
    {
        uint32 quest_id = *iter;
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_MONTHLYQUESTSTATUS);
        stmt->setUInt32(0, GetGUIDLow());
        stmt->setUInt32(1, quest_id);
        trans->Append(stmt);
    }

    m_MonthlyQuestChanged = false;
}

void Player::_SaveSkills(SQLTransaction& trans)
{
    PreparedStatement* stmt = NULL;
    // we don't need transactions here.
    for (SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end();)
    {
        if (itr->second.uState == SKILL_UNCHANGED)
        {
            ++itr;
            continue;
        }

        if (itr->second.uState == SKILL_DELETED)
        {
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SKILL_BY_SKILL);
            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt32(1, itr->first);
            trans->Append(stmt);

            mSkillStatus.erase(itr++);
            continue;
        }

        uint16 field = itr->second.pos / 2;
        uint8 offset = itr->second.pos & 1;

        uint16 value = GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset);
        uint16 max = GetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset);

        switch (itr->second.uState)
        {
            case SKILL_NEW:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SKILLS);
                stmt->setUInt32(0, GetGUIDLow());
                stmt->setUInt16(1, uint16(itr->first));
                stmt->setUInt16(2, value);
                stmt->setUInt16(3, max);
                trans->Append(stmt);
                break;
            case SKILL_CHANGED:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_UDP_CHAR_SKILLS);
                stmt->setUInt16(0, value);
                stmt->setUInt16(1, max);
                stmt->setUInt32(2, GetGUIDLow());
                stmt->setUInt16(3, uint16(itr->first));
                trans->Append(stmt);
                break;
            default:
                break;
        }

        itr->second.uState = SKILL_UNCHANGED;
        ++itr;
    }
}

#define SKILL_MOUNT     777
#define SKILL_MINIPET   778

void Player::_SaveSpells(SQLTransaction& charTrans, SQLTransaction& accountTrans)
{
    PreparedStatement* stmt = NULL;
    
    uint32 l_GroupRealmMask     = sWorld->getIntConfig(WorldIntConfigs::CONFIG_ACCOUNT_BIND_GROUP_MASK);
    uint32 l_ShopGroupRealmMask = sWorld->getIntConfig(WorldIntConfigs::CONFIG_ACCOUNT_BIND_SHOP_GROUP_MASK);

    for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end();)
    {
        if (!itr->second)
            continue;

        if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
        {
            if (const SpellInfo* spell = sSpellMgr->GetSpellInfo(itr->first))
            {
                if (GetSession() && ((spell->IsAbilityOfSkillType(SKILL_MOUNT) && !(spell->AttributesEx10 & SPELL_ATTR10_MOUNT_IS_NOT_ACCOUNT_WIDE))
                    || spell->IsAbilityOfSkillType(SKILL_MINIPET))
                    && sWorld->CanBeSaveInLoginDatabase())
                {
                    /*stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_CHAR_SPELL_BY_SPELL);
                    stmt->setUInt32(0, itr->first);
                    stmt->setUInt32(1, GetSession()->GetAccountId());
                    accountTrans->Append(stmt);*/
                }
                else
                {
                    stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_SPELL_BY_SPELL);
                    stmt->setUInt32(0, itr->first);
                    stmt->setUInt32(1, GetGUIDLow());
                    charTrans->Append(stmt);
                }
            }
        }

        /// add only changed/new not dependent spells
        if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
        {
            if (const SpellInfo* spell = sSpellMgr->GetSpellInfo(itr->first))
            {
                if (GetSession() && ((spell->IsAbilityOfSkillType(SKILL_MOUNT) && ((spell->AttributesEx10 & SPELL_ATTR10_MOUNT_IS_NOT_ACCOUNT_WIDE) == 0))
                    || spell->IsAbilityOfSkillType(SKILL_MINIPET))
                    && sWorld->CanBeSaveInLoginDatabase())
                {
                    stmt = LoginDatabase.GetPreparedStatement(LOGIN_INS_CHAR_SPELL);
                    stmt->setUInt32(0, GetSession()->GetAccountId());
                    stmt->setUInt32(1, itr->first);
                    stmt->setBool(2, itr->second->active);
                    stmt->setBool(3, itr->second->disabled);
                    stmt->setBool(4, itr->second->IsMountFavorite);
                    stmt->setUInt32(5, itr->second->FromShopItem ? l_ShopGroupRealmMask : l_GroupRealmMask);
                    stmt->setUInt32(6, itr->second->FromShopItem ? l_ShopGroupRealmMask : l_GroupRealmMask);

                    accountTrans->Append(stmt);
                }
                else
                {
                    stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_SPELL);
                    stmt->setUInt32(0, GetGUIDLow());
                    stmt->setUInt32(1, itr->first);
                    stmt->setBool(2, itr->second->active);
                    stmt->setBool(3, itr->second->disabled);
                    stmt->setBool(4, itr->second->IsMountFavorite);
                    charTrans->Append(stmt);
                }
            }
        }

        if (itr->second->state == PLAYERSPELL_REMOVED)
        {
            delete itr->second;
            m_spells.erase(itr++);
        }
        else
        {
            itr->second->state = PLAYERSPELL_UNCHANGED;
            ++itr;
        }
    }
}

// save player stats -- only for external usage
// real stats will be recalculated on player login
void Player::_SaveStats(SQLTransaction& trans)
{
    // check if stat saving is enabled and if char level is high enough
    if (!sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE) || getLevel() < sWorld->getIntConfig(CONFIG_MIN_LEVEL_STAT_SAVE))
        return;

    PreparedStatement* stmt = NULL;

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_STATS);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);

    uint8 index = 0;

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_STATS);
    stmt->setUInt32(index++, GetGUIDLow());
    stmt->setUInt32(index++, GetMaxHealth());

    for (uint8 i = 0; i < MAX_POWERS_PER_CLASS; ++i)
        stmt->setUInt32(index++, GetMaxPower(Powers(i)));

    for (uint8 i = 0; i < MAX_STATS; ++i)
        stmt->setUInt32(index++, GetStat(Stats(i)));

    for (int i = 0; i < MAX_SPELL_SCHOOL; ++i)
        stmt->setUInt32(index++, GetResistance(SpellSchools(i)));

    stmt->setFloat(index++, GetFloatValue(PLAYER_FIELD_BLOCK_PERCENTAGE));
    stmt->setFloat(index++, GetFloatValue(PLAYER_FIELD_DODGE_PERCENTAGE));
    stmt->setFloat(index++, GetFloatValue(PLAYER_FIELD_PARRY_PERCENTAGE));
    stmt->setFloat(index++, GetFloatValue(PLAYER_FIELD_CRIT_PERCENTAGE));
    stmt->setFloat(index++, GetFloatValue(PLAYER_FIELD_RANGED_CRIT_PERCENTAGE));
    stmt->setFloat(index++, GetFloatValue(PLAYER_FIELD_SPELL_CRIT_PERCENTAGE));
    stmt->setUInt32(index++, GetUInt32Value(UNIT_FIELD_ATTACK_POWER));
    stmt->setUInt32(index++, GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER));
    stmt->setUInt32(index++, GetBaseSpellPowerBonus());
    stmt->setUInt32(index++, GetUInt32Value(PLAYER_FIELD_COMBAT_RATINGS + CR_RESILIENCE_PLAYER_DAMAGE_TAKEN));

    trans->Append(stmt);
}

void Player::_SaveCharacterGarrisonTavernDatas(SQLTransaction& p_Transaction)
{
    MS::Garrison::Manager* l_GarrisonMgr = GetGarrison();

    if (l_GarrisonMgr == nullptr)
        return;

    PreparedStatement* l_Stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GARRISON_DAILY_TAVERN_DATA_CHAR);
    l_Stmt->setUInt32(0, GetGUIDLow());
    p_Transaction->Append(l_Stmt);

    for (uint32 l_TavernData : l_GarrisonMgr->GetGarrisonTavernDatas())
    {
        l_Stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GARRISON_DAILY_TAVERN_DATA_CHAR);
        l_Stmt->setUInt32(0, GetGUIDLow());
        l_Stmt->setUInt32(1, l_TavernData);
        p_Transaction->Append(l_Stmt);
    }
}

void Player::outDebugValues() const
{
    if (!sLog->ShouldLog(LOG_FILTER_UNITS, LOG_LEVEL_DEBUG))
        return;

    sLog->outDebug(LOG_FILTER_UNITS, "HP is: \t\t\t%u\t\tMP is: \t\t\t%u", GetMaxHealth(), GetMaxPower(POWER_MANA));
    sLog->outDebug(LOG_FILTER_UNITS, "AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f", GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
    sLog->outDebug(LOG_FILTER_UNITS, "INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f", GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
    sLog->outDebug(LOG_FILTER_UNITS, "STAMINA is: \t\t%f", GetStat(STAT_STAMINA));
    sLog->outDebug(LOG_FILTER_UNITS, "Armor is: \t\t%u\t\tBlock is: \t\t%f", GetArmor(), GetFloatValue(PLAYER_FIELD_BLOCK_PERCENTAGE));
    sLog->outDebug(LOG_FILTER_UNITS, "HolyRes is: \t\t%u\t\tFireRes is: \t\t%u", GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
    sLog->outDebug(LOG_FILTER_UNITS, "NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u", GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
    sLog->outDebug(LOG_FILTER_UNITS, "ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u", GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
    sLog->outDebug(LOG_FILTER_UNITS, "MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f", GetFloatValue(UNIT_FIELD_MIN_DAMAGE), GetFloatValue(UNIT_FIELD_MAX_DAMAGE));
    sLog->outDebug(LOG_FILTER_UNITS, "MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f", GetFloatValue(UNIT_FIELD_MIN_OFF_HAND_DAMAGE), GetFloatValue(UNIT_FIELD_MAX_OFF_HAND_DAMAGE));
    sLog->outDebug(LOG_FILTER_UNITS, "MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f", GetFloatValue(UNIT_FIELD_MIN_RANGED_DAMAGE), GetFloatValue(UNIT_FIELD_MAX_RANGED_DAMAGE));
    sLog->outDebug(LOG_FILTER_UNITS, "ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u", GetAttackTime(WeaponAttackType::BaseAttack), GetAttackTime(WeaponAttackType::RangedAttack));
}

/*********************************************************/
/***               FLOOD FILTER SYSTEM                 ***/
/*********************************************************/
void Player::UpdateSpeakTime()
{
    // ignore chat spam protection for GMs in any mode
    if (!AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()))
        return;

    time_t current = time (NULL);
    if (m_speakTime > current)
    {
        uint32 max_count = sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
        if (!max_count)
            return;

        ++m_speakCount;
        if (m_speakCount >= max_count)
        {
            // prevent overwrite mute time, if message send just before mutes set, for example.
            time_t new_mute = current + sWorld->getIntConfig(CONFIG_CHATFLOOD_MUTE_TIME);
            if (GetSession()->m_muteTime < new_mute)
                GetSession()->m_muteTime = new_mute;

            m_speakCount = 0;
        }
    }
    else
        m_speakCount = 0;

    m_speakTime = current + sWorld->getIntConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
}

bool Player::UpdatePmChatTime()
{
    // ignore chat spam protection for GMs in any mode
    if (!AccountMgr::IsPlayerAccount(GetSession()->GetSecurity()))
        return true;

    time_t current = time (NULL);
    if (m_pmChatTime > current)
    {
        uint32 max_count = sWorld->getIntConfig(CONFIG_CHATFLOOD_PRIVATE_MESSAGE_COUNT);
        if (!max_count)
            return true;

        ++m_pmChatCount;
        if (m_pmChatCount >= max_count)
            return false;
    }
    else
        m_pmChatCount = 0;

    m_pmChatTime = current + sWorld->getIntConfig(CONFIG_CHATFLOOD_PRIVATE_MESSAGE_DELAY);
    return true;
}

bool Player::CanSpeak() const
{
    return  GetSession()->m_muteTime <= time (NULL);
}

/*********************************************************/
/***              LOW LEVEL FUNCTIONS:Notifiers        ***/
/*********************************************************/
void Player::SavePositionInDB(uint32 mapid, float x, float y, float z, float o, uint32 zone, uint64 guid)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_CHARACTER_POSITION);

    stmt->setFloat(0, x);
    stmt->setFloat(1, y);
    stmt->setFloat(2, z);
    stmt->setFloat(3, o);
    stmt->setUInt16(4, uint16(mapid));
    stmt->setUInt16(5, uint16(zone));
    stmt->setUInt32(6, GUID_LOPART(guid));

    CharacterDatabase.Execute(stmt);
}

void Player::SetUInt32ValueInArray(Tokenizer& tokens, uint16 index, uint32 value) ///< value is unused<--- The function 'SetUInt32ValueInArray' is never used.
{
    char buf[11];<--- Variable 'buf' is not assigned a value.

    if (index >= tokens.size())
        return;

    tokens[index] = buf;
}

void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHAR_PLAYERBYTES2);
    stmt->setUInt32(0, GUID_LOPART(guid));
    PreparedQueryResult result = CharacterDatabase.Query(stmt);

    if (!result)
        return;

    Field* fields = result->Fetch();

    uint32 playerBytes2 = fields[0].GetUInt32();
    playerBytes2 &= ~0xFF;
    playerBytes2 |= facialHair;

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GENDER_PLAYERBYTES);

    stmt->setUInt8(0, gender);
    stmt->setUInt32(1, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24));
    stmt->setUInt32(2, playerBytes2);
    stmt->setUInt32(3, GUID_LOPART(guid));

    CharacterDatabase.Execute(stmt);
}

void Player::SendAttackSwingError(AttackSwingError p_Error)
{
    WorldPacket l_Data(SMSG_ATTACK_SWING_ERROR, 1);
    l_Data.WriteBits(p_Error, 2);
    l_Data.FlushBits();

    GetSession()->SendPacket(&l_Data);
}

void Player::SendAttackSwingCancelAttack()
{
    WorldPacket data(SMSG_CANCEL_COMBAT, 0);
    GetSession()->SendPacket(&data);
}

void Player::SendAutoRepeatCancel(Unit* p_Target)
{
    WorldPacket l_Data(SMSG_CANCEL_AUTO_REPEAT);
    l_Data.appendPackGUID(p_Target->GetGUID());
    GetSession()->SendPacket(&l_Data);
}

void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
{
    WorldPacket data(SMSG_EXPLORATION_EXPERIENCE, 8);
    data << uint32(Area);
    data << uint32(Experience);
    GetSession()->SendPacket(&data);
}

void Player::SendDungeonDifficulty(int32 p_ForcedDifficulty /*= -1*/)
{
    WorldPacket data(SMSG_SET_DUNGEON_DIFFICULTY, 4);
    data << uint32(p_ForcedDifficulty == -1 ? GetDungeonDifficultyID() : p_ForcedDifficulty);
    GetSession()->SendPacket(&data);
}

void Player::SendRaidDifficulty(bool p_Legacy, int32 forcedDifficulty)
{
    WorldPacket data(SMSG_SET_RAID_DIFFICULTY, 4 + 1);
    data << uint32(forcedDifficulty == -1 ? (p_Legacy ? GetLegacyRaidDifficultyID () : GetRaidDifficultyID()) : forcedDifficulty);
    data << uint8(p_Legacy);
    GetSession()->SendPacket(&data);
}

void Player::SendResetFailedNotify()
{
    WorldPacket data(SMSG_RESET_FAILED_NOTIFY);
    GetSession()->SendPacket(&data);
}

/// Reset all solo instances and optionally send a message on success for each
void Player::ResetInstances(uint8 method, bool isRaid, bool isLegacy)
{
    // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN

    // we assume that when the difficulty changes, all instances that can be reset will be
    Difficulty diff = GetDungeonDifficultyID();
    if (isRaid)
    {
        if (!isLegacy)
            diff = GetRaidDifficultyID();
        else
            diff = GetLegacyRaidDifficultyID();
    }

    for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
    {
        InstanceSave* p = itr->second.save;
        const MapEntry* entry = sMapStore.LookupEntry(itr->first);
        if (!entry || entry->IsRaid() != isRaid || !p->CanReset())
        {
            ++itr;
            continue;
        }

        if (method == INSTANCE_RESET_ALL)
        {
            // the "reset all instances" method can only reset normal maps
            if (entry->instanceType == MAP_RAID || diff == DifficultyRaidHeroic)
            {
                ++itr;
                continue;
            }
        }

        // if the map is loaded, reset it
        Map* map = sMapMgr->FindMap(p->GetMapId(), p->GetInstanceId());
        if (map && map->IsDungeon())
            if (!((InstanceMap*)map)->Reset(method))
            {
                ++itr;
                continue;
            }

        // since this is a solo instance there should not be any players inside
        if (method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
            SendResetInstanceSuccess(p->GetMapId());

        p->DeleteFromDB();
        m_boundInstances[diff].erase(itr++);

        // the following should remove the instance save from the manager and delete it as well
        p->RemovePlayer(this);
    }
}

void Player::SendResetInstanceSuccess(uint32 p_MapID)
{
    WorldPacket data(SMSG_INSTANCE_RESET, 4);
    data << uint32(p_MapID);
    GetSession()->SendPacket(&data);
}

void Player::SendResetInstanceFailed(ResetFailedReason p_Reason, uint32 p_MapID)
{
    /*reasons for instance reset failure:
    // 0: There are players inside the instance.
    // 1: There are players offline in your party.
    // 2>: There are players in your party attempting to zone into an instance.
    */
    WorldPacket data(SMSG_INSTANCE_RESET_FAILED);
    data << uint32(p_MapID);
    data.WriteBits(p_Reason, 2);
    GetSession()->SendPacket(&data);
}

/*********************************************************/
/***              Update timers                        ***/
/*********************************************************/
///checks the 15 afk reports per 5 minutes limit
void Player::UpdateAfkReport(time_t currTime)
{
    if (m_bgData.bgAfkReportedTimer <= currTime)
    {
        m_bgData.bgAfkReportedCount = 0;
        m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
    }
}

void Player::UpdateContestedPvP(uint32 diff)
{
    if (!m_contestedPvPTimer||isInCombat())
        return;
    if (m_contestedPvPTimer <= diff)
    {
        ResetContestedPvP();
    }
    else
        m_contestedPvPTimer -= diff;
}

void Player::UpdatePvPFlag(time_t currTime)
{
    if (!IsPvP() || InBattleground() || InArena())
        return;
    if (pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300) || pvpInfo.inHostileArea)
        return;

    UpdatePvP(false);
}

void Player::UpdateDuelFlag(time_t currTime)
{
    if (!m_Duel || m_Duel->startTimer == 0 ||currTime < m_Duel->startTimer + 3)
        return;

    sScriptMgr->OnPlayerDuelStart(this, m_Duel->opponent);

    SetUInt32Value(PLAYER_FIELD_DUEL_TEAM, 1);
    m_Duel->opponent->SetUInt32Value(PLAYER_FIELD_DUEL_TEAM, 2);

    // cleanup combo points
    ClearComboPoints();
    m_Duel->opponent->ClearComboPoints();

    m_Duel->startTimer = 0;
    m_Duel->startTime  = currTime;
    m_Duel->started    = true;
    m_Duel->opponent->m_Duel->startTimer = 0;
    m_Duel->opponent->m_Duel->startTime  = currTime;
    m_Duel->opponent->m_Duel->started    = true;
}

Pet* Player::GetPet() const
{
    if (uint64 pet_guid = GetPetGUID())
    {
        if (!IS_PET_GUID(pet_guid))
            return NULL;

        Pet* pet = ObjectAccessor::GetPet(*this, pet_guid);

        if (!pet)
            return NULL;

        if (IsInWorld() && pet)
            return pet;

        //there may be a guardian in slot
        //sLog->outError(LOG_FILTER_PLAYER, "Player::GetPet: Pet %u not exist.", GUID_LOPART(pet_guid));
        //const_cast<Player*>(this)->SetPetGUID(0);
    }

    return NULL;
}

void Player::RemovePet(Pet* pet, PetSlot mode, bool returnreagent, bool stampeded)
{
    if (!pet)
        pet = GetPet();

    if (pet)
    {
        sLog->outDebug(LOG_FILTER_PETS, "RemovePet %u, %u, %u", pet->GetEntry(), mode, returnreagent);

        if (pet->m_removed)
            return;
    }

    if (!pet || pet->GetOwnerGUID() != GetGUID())
        return;

    if (mode == PET_SLOT_ACTUAL_PET_SLOT)
        mode = PetSlot(pet->GetSlot());

    pet->CombatStop();
    // only if current pet in slot
    pet->SavePetToDB(mode, stampeded);

    if (pet->getPetType() != HUNTER_PET)
        SetMinion(pet, false, PET_SLOT_UNK_SLOT, stampeded);
    else
        SetMinion(pet, false, PET_SLOT_ACTUAL_PET_SLOT, stampeded);

    pet->AddObjectToRemoveList();
    pet->m_removed = true;

    if (pet->isControlled() && !stampeded)
    {
        SendRemoveControlBar();
        if (GetGroup())
            SetGroupUpdateFlag(GROUP_UPDATE_PET);
    }

    // Spirit Bond
    if (HasSpell(109212) && HasAura(118694))
        RemoveAura(118694);

    // Kindred Spirits
    if (HasAura(56315))
        pet->RemoveAura(56315);

    // Soul Link
    if (Unit* owner = pet->GetOwner())
    {
        if (owner->IsPlayer() && owner->ToPlayer()->HasSpell(108415))
        {
            owner->RemoveAura(108446);
            pet->RemoveAura(108446);
        }
    }
}

void Player::StopCastingCharm()
{
    Unit* charm = GetCharm();
    if (!charm)
        return;

    if (charm->GetTypeId() == TYPEID_UNIT)
    {
        if (charm->ToCreature()->HasUnitTypeMask(UNIT_MASK_PUPPET))
            ((Puppet*)charm)->UnSummon();
        else if (charm->IsVehicle())
            ExitVehicle();
    }
    if (GetCharmGUID())
        charm->RemoveCharmAuras();

    if (GetCharmGUID())
    {
        sLog->outFatal(LOG_FILTER_PLAYER, "Player %s (GUID: " UI64FMTD " is not able to uncharm unit (GUID: " UI64FMTD " Entry: %u, Type: %u)", GetName(), GetGUID(), GetCharmGUID(), charm->GetEntry(), charm->GetTypeId());
        if (charm->GetCharmerGUID())
        {
            sLog->outFatal(LOG_FILTER_PLAYER, "Charmed unit has charmer guid " UI64FMTD, charm->GetCharmerGUID());
            ASSERT(false);
        }
        else
            SetCharm(charm, false);
    }
}

void Player::BuildPlayerChat(WorldPacket* p_Data, Player* p_Target, uint8 p_MsgType, std::string const& p_Text, uint32 p_LangID, char const* p_AddonPrefix /*= nullptr*/, std::string const& p_Channel /*= ""*/) const
{
    uint32 l_SenderNameLen = strlen(GetName());
    uint64 l_GuildGuid = const_cast<Player*>(this)->GetGuild() ? const_cast<Player*>(this)->GetGuild()->GetGUID() : 0;

    p_Data->Initialize(SMSG_CHAT, 800);
    *p_Data << uint8(p_MsgType);
    *p_Data << uint8(p_LangID);
    p_Data->appendPackGUID(GetGUID());
    p_Data->appendPackGUID(l_GuildGuid);
    p_Data->appendPackGUID(0);
    p_Data->appendPackGUID(p_Target != nullptr ? p_Target->GetGUID() : 0);
    *p_Data << uint32(g_RealmID);
    *p_Data << uint32(g_RealmID);
    p_Data->appendPackGUID(GetGroup() ? GetGroup()->GetGUID() : 0);
    *p_Data << uint32(0);     ///< AchievementID
    *p_Data << float(0);      ///< DisplayTime

    p_Data->WriteBits(l_SenderNameLen, 11);
    p_Data->WriteBits(0, 11); ///< TargetNameLen
    p_Data->WriteBits(p_AddonPrefix ? strlen(p_AddonPrefix) : 0, 5);
    p_Data->WriteBits(p_Channel.length(), 7);
    p_Data->WriteBits(p_Text.length(), 12);
    p_Data->WriteBits(GetChatTag(), 11);
    p_Data->WriteBit(false);  ///< hide chat log
    p_Data->WriteBit(false);  ///< Faker sender name
    p_Data->FlushBits();

    p_Data->WriteString(GetName());
    p_Data->WriteString(p_AddonPrefix ? p_AddonPrefix : "");
    p_Data->WriteString(p_Channel);
    p_Data->WriteString(p_Text);
}

void Player::Say(std::string const& p_Text, uint32 const p_LangID)
{
    std::string l_Text(p_Text);
    sScriptMgr->OnPlayerChat(this, CHAT_MSG_SAY, p_LangID, l_Text);

    std::list<Player*> l_PlayerList;
    GetPlayerListInGrid(l_PlayerList, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true);

    for (Player* l_Target : l_PlayerList)
    {
        if (PlayerSocial* l_Social = l_Target->GetSocial())
        {
            if (l_Social->HasIgnore(GUID_LOPART(GetGUID())))
                continue;
        }

        if (WorldSession* l_Session = l_Target->GetSession())
        {
            WorldPacket l_Data;
            BuildPlayerChat(&l_Data, l_Target, CHAT_MSG_SAY, l_Text, p_LangID);
            l_Session->SendPacket(&l_Data);
        }
    }
}

void Player::Yell(std::string const& p_Text, uint32 const p_LangID)
{
    std::string l_Text(p_Text);
    sScriptMgr->OnPlayerChat(this, CHAT_MSG_YELL, p_LangID, l_Text);

    std::list<Player*> l_PlayerList;
    GetPlayerListInGrid(l_PlayerList, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_YELL), true);

    for (Player* l_Target : l_PlayerList)
    {
        if (WorldSession* l_Session = l_Target->GetSession())
        {
            WorldPacket l_Data;
            BuildPlayerChat(&l_Data, l_Target, CHAT_MSG_YELL, l_Text, p_LangID);
            l_Session->SendPacket(&l_Data);
        }
    }
}

void Player::TextEmote(std::string const& p_Text)
{
    std::string l_Text(p_Text);
    sScriptMgr->OnPlayerChat(this, CHAT_MSG_EMOTE, LANG_UNIVERSAL, l_Text);

    std::list<Player*> l_PlayerList;
    GetPlayerListInGrid(l_PlayerList, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE), true);

    for (Player* l_Target : l_PlayerList)
    {
        if (!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) && l_Target->GetTeamId() != GetTeamId() && !l_Target->isGameMaster())
            continue;

        if (WorldSession* l_Session = l_Target->GetSession())
        {
            WorldPacket l_Data;
            /// No specific target needed
            BuildPlayerChat(&l_Data, nullptr, CHAT_MSG_EMOTE, l_Text, LANG_UNIVERSAL);
            l_Session->SendPacket(&l_Data);
        }
    }
}

void Player::WhisperAddon(std::string const& p_Text, std::string const& p_Prefix, Player* p_Receiver)
{
    std::string l_Text(p_Text);
    sScriptMgr->OnPlayerChat(this, CHAT_MSG_WHISPER, LANG_UNIVERSAL, l_Text, p_Receiver);

    if (!p_Receiver->GetSession()->IsAddonRegistered(p_Prefix))
        return;

    WorldPacket l_Data;
    BuildPlayerChat(&l_Data, nullptr, CHAT_MSG_WHISPER, l_Text, LANG_ADDON, p_Prefix.c_str());
    p_Receiver->GetSession()->SendPacket(&l_Data);
}

void Player::Whisper(std::string const& p_Text, uint32 p_LangID, uint64 p_Receiver)
{
    Player* l_Target = ObjectAccessor::FindPlayer(p_Receiver);
    if (l_Target == nullptr)
        return;

    std::string l_Text(p_Text);
    sScriptMgr->OnPlayerChat(this, CHAT_MSG_WHISPER, p_LangID, l_Text, l_Target);

    if (l_Target->GetSocial()->HasIgnore(GetGUIDLow()))
    {
        WorldPacket l_Data;
        ChatHandler::FillMessageData(&l_Data, GetSession(), CHAT_MSG_IGNORED, LANG_UNIVERSAL, NULL, GetGUID(), GetName(), NULL);
        GetSession()->SendPacket(&l_Data);
        return;
    }

    /// When player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
    if (!l_Target->isDND() || isGameMaster())
    {
        WorldPacket l_Data;
        BuildPlayerChat(&l_Data, l_Target, CHAT_MSG_WHISPER, l_Text, p_LangID);
        l_Target->GetSession()->SendPacket(&l_Data);

        l_Target->BuildPlayerChat(&l_Data, this, CHAT_MSG_WHISPER_INFORM, l_Text, p_LangID);
        GetSession()->SendPacket(&l_Data);
    }
    else ///< Announce to player that player he is whispering to is dnd and cannot receive his message
        ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, l_Target->GetName(), l_Target->dndMsg.c_str());

    if (!IsAcceptWhispers() && !isGameMaster() && !l_Target->isGameMaster())
    {
        SetAcceptWhispers(true);
        ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
    }

    /// Announce to player that player he is whispering to is afk
    if (l_Target->isAFK())
        ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, l_Target->GetName(), l_Target->afkMsg.c_str());

    /// If player whisper someone, auto turn of dnd to be able to receive an answer
    if (isDND() && !l_Target->isGameMaster())
        ToggleDND();
}

void Player::PetSpellInitialize()
{
    Pet* l_Pet = GetPet();
    if (!l_Pet)
        return;

    CharmInfo* l_CharmInfo = l_Pet->GetCharmInfo();

    uint32 l_ActionCount = 0;
    if (l_Pet->IsPermanentPetFor(this))
    {
        for (PetSpellMap::iterator l_Itr = l_Pet->m_spells.begin(); l_Itr != l_Pet->m_spells.end(); ++l_Itr)
        {
            if (l_Itr->second.state != PETSPELL_REMOVED)
                ++l_ActionCount;
        }
    }

    uint32 l_CooldownCount        = l_Pet->m_CreatureSpellCooldowns.size();
    uint32 l_PetSpellHistoryCount = 0;
    uint32 l_TimeLimit            = l_Pet->GetDuration();
    uint32 l_PetModeAndOrders     = l_Pet->GetReactState() | l_CharmInfo->GetCommandState() << 8 | 0 << 16;     // PetModeAndOrders have : React state, Command State & flags
    uint16 l_CreatureFamily       = l_Pet->GetCreatureTemplate()->family;
    uint16 l_Specialization       = l_Pet->GetSpecializationId();
    ObjectGuid l_PetGUID          = l_Pet->GetGUID();

    WorldPacket l_Data(SMSG_PET_SPELLS_MESSAGE, 500);
    l_Data.appendPackGUID(l_PetGUID);           ///< PetGUID
    l_Data << uint16(l_CreatureFamily);         ///< CreatureFamily
    l_Data << uint16(l_Specialization);         ///< Specialization
    l_Data << uint32(l_TimeLimit);              ///< TimeLimit
    l_Data << uint32(l_PetModeAndOrders);       ///< PetModeAndOrders

    // action bar loop
    l_CharmInfo->BuildActionBar(&l_Data);

    l_Data << uint32(l_ActionCount);
    l_Data << uint32(l_CooldownCount);
    l_Data << uint32(l_PetSpellHistoryCount);

    if (l_Pet->IsPermanentPetFor(this))
    {
        for (PetSpellMap::iterator itr = l_Pet->m_spells.begin(); itr != l_Pet->m_spells.end(); ++itr)
        {
            if (itr->second.state == PETSPELL_REMOVED)
                continue;

            l_Data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first, itr->second.active));  ///< Actions
        }
    }

    time_t l_Now = sWorld->GetGameTime();
    for (CreatureSpellCooldowns::const_iterator l_Itr = l_Pet->m_CreatureSpellCooldowns.begin(); l_Itr != l_Pet->m_CreatureSpellCooldowns.end(); ++l_Itr)
    {
        uint32 l_SpellID          = 0;
        uint32 l_Duration         = 0;
        uint32 l_CategoryDuration = 0;
        uint16 l_Category         = 0;

        SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_Itr->first);
        if (l_SpellInfo != nullptr)
        {
            l_Duration = (l_Itr->second > l_Now) ? (l_Itr->second - l_Now) * IN_MILLISECONDS : 0;
            l_SpellID = l_Itr->second;

            CreatureSpellCooldowns::const_iterator l_CategoryItr = l_Pet->m_CreatureCategoryCooldowns.find(l_SpellInfo->GetCategory());
            if (l_CategoryItr != l_Pet->m_CreatureCategoryCooldowns.end())
            {
                l_Category         = l_SpellInfo->GetCategory();
                l_CategoryDuration = (l_CategoryItr->second > l_Now) ? (l_CategoryItr->second - l_Now) * IN_MILLISECONDS : 0;
            }
        }

        l_Data << uint32(l_SpellID);
        l_Data << uint32(l_Duration);
        l_Data << uint32(l_CategoryDuration);
        l_Data << uint16(l_Category);
    }

    //for (uint32 l_I = 0; l_I < l_PetSpellHistoryCount; ++l_I)
    //{
    //    l_Data << int32(l_PetSpellHistory[l_I].CategoryID);
    //    l_Data << int32(l_PetSpellHistory[l_I].RecoveryTime);
    //    l_Data << int32(l_PetSpellHistory[l_I].ConsumedCharges);
    //}

    GetSession()->SendPacket(&l_Data);
}

void Player::PossessSpellInitialize()
{
    Unit* l_Charm = GetCharm();
    if (!l_Charm)
        return;

    CharmInfo* l_CharmInfo = l_Charm->GetCharmInfo();
    if (!l_CharmInfo)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player::PossessSpellInitialize(): charm (" UI64FMTD ") has no charminfo!", l_Charm->GetGUID());
        return;
    }

    uint32 l_CooldownCount        = 0;
    uint32 l_ActionCount          = 0;
    uint32 l_PetSpellHistoryCount = 0;
    uint32 l_TimeLimit            = 0;
    uint32 l_PetModeAndOrders     = 0;
    uint16 l_CreatureFamily       = 0;
    uint16 l_Specialization       = 0;
    ObjectGuid l_PetGUID          = l_Charm->GetGUID();

    WorldPacket l_Data(SMSG_PET_SPELLS_MESSAGE, 500);
    l_Data.appendPackGUID(l_PetGUID);           ///< PetGUID
    l_Data << uint16(l_CreatureFamily);         ///< CreatureFamily
    l_Data << uint16(l_Specialization);         ///< Specialization
    l_Data << uint32(l_TimeLimit);              ///< TimeLimit
    l_Data << uint32(l_PetModeAndOrders);       ///< PetModeAndOrders

    l_CharmInfo->BuildActionBar(&l_Data);

    l_Data << uint32(l_ActionCount);
    l_Data << uint32(l_CooldownCount);
    l_Data << uint32(l_PetSpellHistoryCount);

    GetSession()->SendPacket(&l_Data);
}

void Player::VehicleSpellInitialize()
{
    Creature* l_Vehicle = GetVehicleCreatureBase();
    if (!l_Vehicle)
        return;

    uint32 l_CooldownCount        = l_Vehicle->m_CreatureSpellCooldowns.size();
    uint32 l_ActionCount          = 0;
    uint32 l_PetSpellHistoryCount = 0;
    uint32 l_TimeLimit            = l_Vehicle->isSummon() ? l_Vehicle->ToTempSummon()->GetTimer() : 0;
    uint32 l_PetModeAndOrders     = l_Vehicle->GetReactState() | 0 << 8 | 0x800 << 16;                  // PetModeAndOrders have : React state, Command State & DisableActions
    uint16 l_CreatureFamily       = l_Vehicle->GetCreatureTemplate()->family;
    uint16 l_Specialization       = 0;                                                                  // I think it's useless in case of vehicle action bar
    ObjectGuid l_PetGUID          = l_Vehicle->GetGUID();

    WorldPacket l_Data(SMSG_PET_SPELLS_MESSAGE, 500);
    l_Data.appendPackGUID(l_PetGUID);           ///< PetGUID
    l_Data << uint16(l_CreatureFamily);         ///< CreatureFamily
    l_Data << uint16(l_Specialization);         ///< Specialization
    l_Data << uint32(l_TimeLimit);              ///< TimeLimit
    l_Data << uint32(l_PetModeAndOrders);       ///< PetModeAndOrders

    for (uint32 l_I = 0; l_I < CREATURE_MAX_SPELLS; ++l_I)
    {
        uint32 l_SpellId = l_Vehicle->m_spells[l_I];
        SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_SpellId);
        if (!l_SpellInfo)
        {
            l_Data << uint16(0) << uint8(0) << uint8(l_I + 8);
            continue;
        }

        if (!sConditionMgr->IsObjectMeetingVehicleSpellConditions(l_Vehicle->GetEntry(), l_SpellId, this, l_Vehicle))
        {
            sLog->outDebug(LOG_FILTER_CONDITIONSYS, "VehicleSpellInitialize: conditions not met for Vehicle entry %u spell %u", l_Vehicle->ToCreature()->GetEntry(), l_SpellId);
            l_Data << uint16(0) << uint8(0) << uint8(l_I + 8);
            continue;
        }

        if (l_SpellInfo->IsPassive())
            l_Vehicle->CastSpell(l_Vehicle, l_SpellId, true);

        l_Data << uint32(MAKE_UNIT_ACTION_BUTTON(l_SpellId, l_I + 8));
    }

    for (uint32 l_I = CREATURE_MAX_SPELLS; l_I < MAX_SPELL_CONTROL_BAR; ++l_I)
        l_Data << uint32(0);

    l_Data << uint32(l_ActionCount);
    l_Data << uint32(l_CooldownCount);
    l_Data << uint32(l_PetSpellHistoryCount);

    //for (uint32 l_I = 0; l_I < l_ActionCount; ++l_ActionCount)
    //    l_Data << (l_Action[l_I]);

    time_t l_Now = sWorld->GetGameTime();
    for (CreatureSpellCooldowns::const_iterator l_Itr = l_Vehicle->m_CreatureSpellCooldowns.begin(); l_Itr != l_Vehicle->m_CreatureSpellCooldowns.end(); ++l_Itr)
    {
        uint32 l_SpellID          = 0;
        uint32 l_Duration         = 0;
        uint32 l_CategoryDuration = 0;
        uint16 l_Category         = 0;

        SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_Itr->first);
        if (l_SpellInfo != nullptr)
        {
            l_Duration = (l_Itr->second > l_Now) ? (l_Itr->second - l_Now) * IN_MILLISECONDS : 0;
            l_SpellID = l_Itr->second;

            CreatureSpellCooldowns::const_iterator l_CategoryItr = l_Vehicle->m_CreatureCategoryCooldowns.find(l_SpellInfo->GetCategory());
            if (l_CategoryItr != l_Vehicle->m_CreatureCategoryCooldowns.end())
            {
                l_Category         = l_SpellInfo->GetCategory();
                l_CategoryDuration = (l_CategoryItr->second > l_Now) ? (l_CategoryItr->second - l_Now) * IN_MILLISECONDS : 0;
            }
        }

        l_Data << uint32(l_SpellID);
        l_Data << uint32(l_Duration);
        l_Data << uint32(l_CategoryDuration);
        l_Data << uint16(l_Category);
    }

    //for (uint32 l_I = 0; l_I < l_PetSpellHistoryCount; ++l_I)
    //{
    //    l_Data << int32(l_PetSpellHistory[l_I].CategoryID);
    //    l_Data << int32(l_PetSpellHistory[l_I].RecoveryTime);
    //    l_Data << int32(l_PetSpellHistory[l_I].ConsumedCharges);
    //}

    GetSession()->SendPacket(&l_Data);
}

void Player::CharmSpellInitialize()
{
    Unit* l_Charm = GetFirstControlled();
    if (!l_Charm)
        return;

    CharmInfo* l_CharmInfo = l_Charm->GetCharmInfo();
    if (!l_CharmInfo)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player::CharmSpellInitialize(): the player's charm (" UI64FMTD ") has no charminfo!", l_Charm->GetGUID());
        return;
    }

    uint32 l_ActionCount = 0;
    if (l_Charm->GetTypeId() != TYPEID_PLAYER)
    {
        for (uint32 l_I = 0; l_I < MAX_SPELL_CHARM; ++l_I)
        {
            if (l_CharmInfo->GetCharmSpell(l_I)->GetAction())
            {
                SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_CharmInfo->GetCharmSpell(l_I)->packedData & 0x00FFFFFF);
                if (l_SpellInfo && !l_SpellInfo->CannotBeAddedToCharm())
                    continue;

                ++l_ActionCount;
            }
        }
    }

    uint32 l_PetModeAndOrders = 0;
    if (l_Charm->GetTypeId() != TYPEID_PLAYER)
        l_PetModeAndOrders = uint8(l_Charm->ToCreature()->GetReactState()) | uint8(l_CharmInfo->GetCommandState()) << 8 | 0 << 16;  // PetModeAndOrders have : React state, Command State & flags

    uint32 l_CooldownCount        = 0;
    uint32 l_PetSpellHistoryCount = 0;
    uint32 l_TimeLimit            = 0;
    uint16 l_CreatureFamily       = 0;
    uint16 l_Specialization       = 0;
    ObjectGuid l_PetGUID          = l_Charm->GetGUID();

    WorldPacket l_Data(SMSG_PET_SPELLS_MESSAGE, 500);
    l_Data.appendPackGUID(l_PetGUID);           ///< PetGUID
    l_Data << uint16(l_CreatureFamily);         ///< CreatureFamily
    l_Data << uint16(l_Specialization);         ///< Specialization
    l_Data << uint32(l_TimeLimit);              ///< TimeLimit
    l_Data << uint32(l_PetModeAndOrders);       ///< PetModeAndOrders

    // action bar loop
    l_CharmInfo->BuildActionBar(&l_Data);

    l_Data << uint32(l_ActionCount);
    l_Data << uint32(l_CooldownCount);
    l_Data << uint32(l_PetSpellHistoryCount);

    if (l_ActionCount)
    {
        for (uint32 i = 0; i < MAX_SPELL_CHARM; ++i)
        {
            CharmSpellInfo* l_CSpell = l_CharmInfo->GetCharmSpell(i);
            SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo(l_CSpell->packedData & 0x00FFFFFF);
            if (l_SpellInfo && !l_SpellInfo->CannotBeAddedToCharm())
                continue;

            if (l_CSpell->GetAction())
                l_Data << uint32(l_CSpell->packedData);
        }
    }

    //for (uint32 l_I = 0; l_I < l_CooldownCount; l_I++)
    //{
    //    l_Data << uint32(l_PetSpellCooldown[l_I].SpellID);
    //    l_Data << uint32(l_PetSpellCooldown[l_I].Duration);
    //    l_Data << uint32(l_PetSpellCooldown[l_I].CategoryDuration);
    //    l_Data << uint16(l_PetSpellCooldown[l_I].Category);
    //}

    //for (uint32 l_I = 0; l_I < l_PetSpellHistoryCount; ++l_I)
    //{
    //    l_Data << int32(l_PetSpellHistory[l_I].CategoryID);
    //    l_Data << int32(l_PetSpellHistory[l_I].RecoveryTime);
    //    l_Data << int32(l_PetSpellHistory[l_I].ConsumedCharges);
    //}

    GetSession()->SendPacket(&l_Data);
}

void Player::SendRemoveControlBar()
{
    uint32 l_CooldownCount = 0;
    uint32 l_ActionCount = 0;
    uint32 l_PetSpellHistoryCount = 0;
    uint32 l_TimeLimit = 0;
    uint32 l_PetModeAndOrders = 0;
    uint16 l_CreatureFamily = 0;
    uint16 l_Specialization = 0;
    ObjectGuid l_PetGUID = 0;

    WorldPacket l_Data(SMSG_PET_SPELLS_MESSAGE, 500);
    l_Data.appendPackGUID(l_PetGUID);           ///< PetGUID
    l_Data << uint16(l_CreatureFamily);         ///< CreatureFamily
    l_Data << uint16(l_Specialization);         ///< Specialization
    l_Data << uint32(l_TimeLimit);              ///< TimeLimit
    l_Data << uint32(l_PetModeAndOrders);       ///< PetModeAndOrders

    for (int l_I = 0; l_I < 10; l_I++)
        l_Data << uint32(0);                    ///< ActionButtons[l_I]

    l_Data << uint32(l_ActionCount);
    l_Data << uint32(l_CooldownCount);
    l_Data << uint32(l_PetSpellHistoryCount);

    GetSession()->SendPacket(&l_Data);
}

bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell)
{
    if (!mod || !spellInfo)
        return false;

    // Mod out of charges
    if (spell && mod->charges == -1 && spell->m_appliedMods.find((Aura*)mod->ownerAura) == spell->m_appliedMods.end())
        return false;

    // +duration to infinite duration spells making them limited
    if (mod->op == SPELLMOD_DURATION && spellInfo->GetDuration() == -1)
        return false;

    return spellInfo->IsAffectedBySpellMod(mod);
}

void Player::AddSpellMod(SpellModifier* p_Modifier, bool p_Apply)
{
    Opcodes l_Opcode = Opcodes((p_Modifier->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER);

    flag128 l_Mask = 0;
    uint32 l_ModifierTypeCount = 0; // count of mods per one mod->op
    uint32 l_MaskIndex = 0;

    WorldPacket l_Packet(l_Opcode);
    ByteBuffer l_Buffer;

    for (int l_EffectIndex = 0; l_EffectIndex < 128; ++l_EffectIndex)
    {
        if (l_EffectIndex != 0 && (l_EffectIndex % 32) == 0)
            l_Mask[l_MaskIndex++] = 0;

        l_Mask[l_MaskIndex] = uint32(1) << (l_EffectIndex - (32 * l_MaskIndex));

        if (p_Modifier->mask & l_Mask)
        {
            float l_Value = p_Modifier->type == SPELLMOD_FLAT ? 0.0f : 1.0f;

            if (p_Modifier->type == SPELLMOD_FLAT)
            {
                for (SpellModList::iterator l_It = m_spellMods[p_Modifier->op].begin(); l_It != m_spellMods[p_Modifier->op].end(); ++l_It)
                    if ((*l_It)->type == p_Modifier->type && (*l_It)->mask & l_Mask)
                        l_Value += float((*l_It)->value);

                l_Value += p_Apply ? float(p_Modifier->value) : float(-p_Modifier->value);
            }
            else
            {
                for (SpellModList::iterator l_It = m_spellMods[p_Modifier->op].begin(); l_It != m_spellMods[p_Modifier->op].end(); ++l_It)
                    if ((*l_It)->type == p_Modifier->type && (*l_It)->mask & l_Mask && (p_Apply || (!p_Apply && p_Modifier != *l_It)))<--- Redundant condition: !p_Apply. 'p_Apply || (!p_Apply && p_Modifier!=*l_It)' is equivalent to 'p_Apply || p_Modifier!=*l_It'
                        AddPct(l_Value, (*l_It)->value);

                if (p_Apply)
                    AddPct(l_Value, p_Modifier->value);
            }

            l_Buffer << float(l_Value);
            l_Buffer << uint8(l_EffectIndex);

            ++l_ModifierTypeCount;
        }
    }

    l_Packet << uint32(1);
    l_Packet << uint8(p_Modifier->op);
    l_Packet << uint32(l_ModifierTypeCount);
    l_Packet.append(l_Buffer);

    SendDirectMessage(&l_Packet);

    if (p_Apply)
        m_spellMods[p_Modifier->op].push_back(p_Modifier);
    else
    {
        m_spellMods[p_Modifier->op].remove(p_Modifier);

        // mods bound to aura will be removed in AuraEffect::~AuraEffect
        if (!p_Modifier->ownerAura)
            delete p_Modifier;
    }
}

// Restore spellmods in case of failed cast
void Player::RestoreSpellMods(Spell* spell, uint32 ownerAuraId, Aura* aura)
{
    if (!spell || spell->m_appliedMods.empty())
        return;

    for (uint8 i=0; i<MAX_SPELLMOD; ++i)
    {
        for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end(); ++itr)
        {
            SpellModifier* mod = *itr;

            // spellmods without aura set cannot be charged
            if (!mod->ownerAura || !mod->ownerAura->IsUsingCharges())
                continue;

            // Restore only specific owner aura mods
            if (ownerAuraId && (ownerAuraId != mod->ownerAura->GetSpellInfo()->Id))
                continue;

            if (aura && mod->ownerAura != aura)
                continue;

            // check if mod affected this spell
            // first, check if the mod aura applied at least one spellmod to this spell
            Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find((Aura*)mod->ownerAura);
            if (iterMod == spell->m_appliedMods.end())
                continue;
            // secondly, check if the current mod is one of the spellmods applied by the mod aura
            if (!(mod->mask & spell->m_spellInfo->SpellFamilyFlags))
                continue;

            // remove from list
            spell->m_appliedMods.erase(iterMod);

            // add mod charges back to mod
            if (mod->charges == -1)
                mod->charges = 1;
            else
                mod->charges++;

            // Do not set more spellmods than avalible
            if (mod->ownerAura->GetCharges() < mod->charges)
                mod->charges = mod->ownerAura->GetCharges();

            // Skip this check for now - aura charges may change due to various reason
            // TODO: trac these changes correctly
            //ASSERT (mod->ownerAura->GetCharges() <= mod->charges);
        }
    }
}

void Player::RestoreAllSpellMods(uint32 ownerAuraId, Aura* aura)
{
    for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
        if (m_currentSpells[i])
            RestoreSpellMods(m_currentSpells[i], ownerAuraId, aura);
}

void Player::RemoveSpellMods(Spell* spell)
{
    if (!spell)
        return;

    // Hack fix for Blizzard with Ice Floes
    if (spell->GetSpellInfo()->Id == 10 && spell->GetCaster())
    {
        if (Aura* l_IceFLoes = spell->GetCaster()->GetAura(108839))
            l_IceFLoes->DropCharge();
    }

    if (spell->m_appliedMods.empty())
        return;

    // Hack fix for "double proc" for pyroblast! + Presence of Mind
    bool magePyroblast = false;

    for (uint8 i=0; i<MAX_SPELLMOD; ++i)
    {
        for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
        {
            SpellModifier* mod = *itr;
            ++itr;

            // spellmods without aura set cannot be charged
            if (!mod->ownerAura || !mod->ownerAura->IsUsingCharges())
                continue;

            // check if mod affected this spell
            Spell::UsedSpellMods::iterator iterMod = spell->m_appliedMods.find((Aura*)mod->ownerAura);
            if (iterMod == spell->m_appliedMods.end())
                continue;

            // remove from list
            spell->m_appliedMods.erase(iterMod);

            if (mod->ownerAura->GetId() == 48108)
                magePyroblast = true;
            else if (mod->ownerAura->GetId() == 12043 && magePyroblast)
                continue;

            /// Camouflage and Camouflage (Subterfuge) have spellModifier with value 0, add specific case
            if (!(mod->ownerAura->GetId() == 117828 && spell->GetSpellInfo()->Id == 116858) && mod->ownerAura->GetId() != 1784 && mod->ownerAura->GetId() != 115191)
                if (((Aura*)mod->ownerAura)->DropCharge(AURA_REMOVE_BY_EXPIRE))
                    itr = m_spellMods[i].begin();
        }
    }
}

void Player::DropModCharge(SpellModifier* mod, Spell* spell)
{
    // don't handle spells with proc_event entry defined
    // this is a temporary workaround, because all spellmods should be handled like that
    if (sSpellMgr->GetSpellProcEvent(mod->spellId))
        return;

    if (spell && mod->ownerAura && mod->charges > 0)
    {
        if (--mod->charges == 0)
            mod->charges = -1;

        spell->m_appliedMods.insert((Aura*)mod->ownerAura);
    }
}

void Player::SetSpellModTakingSpell(Spell* spell, bool apply)
{
    if (!spell || (m_spellModTakingSpell && m_spellModTakingSpell != spell))
        return;

    if (apply && spell->getState() == SPELL_STATE_FINISHED)
        return;

    m_spellModTakingSpell = apply ? spell : NULL;
}

// send Proficiency
void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask)
{
    WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4);
    data << uint32(itemSubclassMask) << uint8(itemClass);
    GetSession()->SendPacket(&data);
}

void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
{
    PreparedStatement* stmt;

    if (type == 10)
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PETITION_SIG_BY_GUID);
    else
    {
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PETITION_SIG_BY_GUID_TYPE);
        stmt->setUInt8(1, uint8(type));
    }

    stmt->setUInt32(0, GUID_LOPART(guid));
    PreparedQueryResult result = CharacterDatabase.Query(stmt);

    if (result)
    {
        do                                                  // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
        {                                                   // and SendPetitionQueryOpcode reads data from the DB
            Field* fields = result->Fetch();
            uint64 ownerguid   = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
            uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);

            // send update if charter owner in game
            Player* owner = ObjectAccessor::FindPlayer(ownerguid);
            if (owner)
                owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
        }
        while (result->NextRow());

        if (type == 10)
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_PETITION_SIGNATURES);

            stmt->setUInt32(0, GUID_LOPART(guid));

            CharacterDatabase.Execute(stmt);
        }
        else
        {
            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE);

            stmt->setUInt32(0, GUID_LOPART(guid));
            stmt->setUInt8(1, uint8(type));

            CharacterDatabase.Execute(stmt);
        }
    }

    SQLTransaction trans = CharacterDatabase.BeginTransaction();
    if (type == 10)
    {
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER);
        stmt->setUInt32(0, GUID_LOPART(guid));
        trans->Append(stmt);

        stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER);
        stmt->setUInt32(0, GUID_LOPART(guid));
        trans->Append(stmt);
    }
    else
    {
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_BY_OWNER_AND_TYPE);
        stmt->setUInt32(0, GUID_LOPART(guid));
        stmt->setUInt8(1, uint8(type));
        trans->Append(stmt);

        stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PETITION_SIGNATURE_BY_OWNER_AND_TYPE);
        stmt->setUInt32(0, GUID_LOPART(guid));
        stmt->setUInt8(1, uint8(type));
        trans->Append(stmt);
    }
    CharacterDatabase.CommitTransaction(trans);
}

void Player::SetRestBonus (float rest_bonus_new)
{
    // Prevent resting on max level
    if (getLevel() >= sWorld->getIntConfig(CONFIG_MAX_PLAYER_LEVEL))
        rest_bonus_new = 0;

    if (rest_bonus_new < 0)
        rest_bonus_new = 0;

    float rest_bonus_max = (float)GetUInt32Value(PLAYER_FIELD_NEXT_LEVEL_XP)*1.5f/2;

    if (rest_bonus_new > rest_bonus_max)
        m_rest_bonus = rest_bonus_max;
    else
        m_rest_bonus = rest_bonus_new;

    // Inner Peace
    if (HasAura(107074))
        m_rest_bonus *= 2;

    float modifier = 1.0f;
    AuraEffectList const& mIncreaseRest = GetAuraEffectsByType(SPELL_AURA_INCREASE_REST_BONUS_PERCENT);
    for (AuraEffectList::const_iterator i = mIncreaseRest.begin(); i != mIncreaseRest.end(); ++i)
        modifier += float((*i)->GetAmount() / 100);

    m_rest_bonus *= modifier;

    // update data for client
    if (GetSession()->IsARecruiter() || (GetSession()->GetRecruiterId() != 0))
        SetByteValue(PLAYER_FIELD_REST_STATE, PLAYER_BYTES_2_OFFSET_REST_STATE, REST_STATE_RAF_LINKED);
    else if (m_rest_bonus > 10)
        SetByteValue(PLAYER_FIELD_REST_STATE, PLAYER_BYTES_2_OFFSET_REST_STATE, REST_STATE_RESTED);              // Set Reststate = Rested
    else if (m_rest_bonus <= 1)
        SetByteValue(PLAYER_FIELD_REST_STATE, PLAYER_BYTES_2_OFFSET_REST_STATE, REST_STATE_NOT_RAF_LINKED);              // Set Reststate = Normal

    //RestTickUpdate
    SetUInt32Value(PLAYER_FIELD_REST_STATE_BONUS_POOL, uint32(m_rest_bonus));
}

bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
{
    if (nodes.size() < 2)
    {
        GetSession()->SendActivateTaxiReply(ERR_TAXINOSUCHPATH);
        return false;
    }

    // not let cheating with start flight in time of logout process || while in combat || has type state: stunned || has type state: root
    if (GetSession()->isLogingOut() || isInCombat() || HasUnitState(UNIT_STATE_STUNNED) || HasUnitState(UNIT_STATE_ROOT))
    {
        GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERBUSY);
        return false;
    }

    if (HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
        return false;

    // taximaster case
    if (npc)
    {
        // not let cheating with start flight mounted
        if (IsMounted())
        {
            GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERALREADYMOUNTED);
            return false;
        }

        if (IsInDisallowedMountForm())
        {
            GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERSHAPESHIFTED);
            return false;
        }

        // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
        if (IsNonMeleeSpellCasted(false))
        {
            GetSession()->SendActivateTaxiReply(ERR_TAXIPLAYERBUSY);
            return false;
        }
    }
    // cast case or scripted call case
    else
    {
        RemoveAurasByType(SPELL_AURA_MOUNTED);

        if (IsInDisallowedMountForm())
            RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT);

        if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
            if (spell->m_spellInfo->Id != spellid)
                InterruptSpell(CURRENT_GENERIC_SPELL, false);

        InterruptSpell(CURRENT_AUTOREPEAT_SPELL, false);

        if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
            if (spell->m_spellInfo->Id != spellid)
                InterruptSpell(CURRENT_CHANNELED_SPELL, true);
    }

    uint32 sourcenode = nodes[0];

    // starting node too far away (cheat?)
    TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
    if (!node)
    {
        GetSession()->SendActivateTaxiReply(ERR_TAXINOSUCHPATH);
        return false;
    }

    uint32 l_MapID = GetMapId();
    /// Special case for taxi in garrison phased map
    for (uint32 l_I = 0; l_I < sGarrSiteLevelStore.GetNumRows(); ++l_I)
    {
        const GarrSiteLevelEntry * l_Entry = sGarrSiteLevelStore.LookupEntry(l_I);

        if (l_Entry && l_Entry->MapID == l_MapID)
        {
            l_MapID = MS::Garrison::Globals::BaseMap;
            break;
        }
    }

    // check node starting pos data set case if provided
    if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
    {
        if (node->MapID != l_MapID ||
            (node->x - GetPositionX())*(node->x - GetPositionX())+
            (node->y - GetPositionY())*(node->y - GetPositionY())+
            (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
            (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
        {
            GetSession()->SendActivateTaxiReply(ERR_TAXITOOFARAWAY);
            return false;
        }
    }
    // node must have pos if taxi master case (npc != NULL)
    else if (npc)
    {
        GetSession()->SendActivateTaxiReply(ERR_TAXIUNSPECIFIEDSERVERERROR);
        return false;
    }
    // Prepare to flight start now

    // stop combat at start taxi flight if any
    CombatStop();

    StopCastingCharm();
    StopCastingBindSight();
    ExitVehicle();

    // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
    TradeCancel(true);

    // clean not finished taxi path if any
    m_taxi.ClearTaxiDestinations();

    // 0 element current node
    m_taxi.AddTaxiDestination(sourcenode);

    // fill destinations path tail
    uint32 sourcepath = 0;
    uint32 totalcost = 0;
    uint32 firstcost = 0;

    uint32 prevnode = sourcenode;
    uint32 lastnode;

    for (uint32 i = 1; i < nodes.size(); ++i)
    {
        uint32 path, cost;

        lastnode = nodes[i];
        sObjectMgr->GetTaxiPath(prevnode, lastnode, path, cost);

        if (!path)
        {
            m_taxi.ClearTaxiDestinations();
            return false;
        }

        totalcost += cost;
        if (i == 1)
            firstcost = cost;

        if (prevnode == sourcenode)
            sourcepath = path;

        m_taxi.AddTaxiDestination(lastnode);

        prevnode = lastnode;
    }

    // get mount model (in case non taximaster (npc == NULL) allow more wide lookup)
    //
    // Hack-Fix for Alliance not being able to use Acherus taxi. There is
    // only one mount ID for both sides. Probably not good to use 315 in case DBC nodes
    // change but I couldn't find a suitable alternative. OK to use class because only DK
    // can use this taxi.
    uint32 mount_display_id = sObjectMgr->GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == nullptr || (sourcenode == 315 && getClass() == CLASS_DEATH_KNIGHT));

    // in spell case allow 0 model
    if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
    {
        GetSession()->SendActivateTaxiReply(ERR_TAXIUNSPECIFIEDSERVERERROR);
        m_taxi.ClearTaxiDestinations();
        return false;
    }

    uint64 money = GetMoney();

    if (npc)
        totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));

    if (money < totalcost)
    {
        GetSession()->SendActivateTaxiReply(ERR_TAXINOTENOUGHMONEY);
        m_taxi.ClearTaxiDestinations();
        return false;
    }

    //Checks and preparations done, DO FLIGHT
    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);

    // prevent stealth flight
    //RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TALK);

    if (sWorld->getBoolConfig(CONFIG_INSTANT_TAXI))
    {
        TaxiNodesEntry const* lastPathNode = sTaxiNodesStore.LookupEntry(nodes[nodes.size()-1]);
        ASSERT(lastPathNode);
        m_taxi.ClearTaxiDestinations();
        ModifyMoney(-int64(totalcost));
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
        TeleportTo(lastPathNode->MapID, lastPathNode->x, lastPathNode->y, lastPathNode->z, GetOrientation());
        return false;
    }
    else
    {
        ModifyMoney(-int64(firstcost));
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, firstcost);
        GetSession()->SendActivateTaxiReply(ERR_TAXIOK);
        GetSession()->SendDoFlight(mount_display_id, sourcepath);
    }
    return true;
}

bool Player::ActivateTaxiPathTo(uint32 taxi_path_id, uint32 spellid /*= 0*/)
{
    TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
    if (!entry)
        return false;

    std::vector<uint32> nodes;

    nodes.resize(2);
    nodes[0] = entry->From;
    nodes[1] = entry->To;

    return ActivateTaxiPathTo(nodes, nullptr, spellid);
}

void Player::CleanupAfterTaxiFlight()
{
    m_taxi.ClearTaxiDestinations();        // not destinations, clear source node
    Dismount();
    RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_TAXI_FLIGHT);
    getHostileRefManager().setOnlineOfflineState(true);
}

void Player::ContinueTaxiFlight() const
{
    uint32 sourceNode = m_taxi.GetTaxiSource();
    if (!sourceNode)
        return;

    sLog->outDebug(LOG_FILTER_UNITS, "WORLD: Restart character %u taxi flight", GetGUIDLow());

    uint32 mountDisplayId = sObjectMgr->GetTaxiMountDisplayId(sourceNode, GetTeam(), true);
    if (!mountDisplayId)
        return;

    uint32 path = m_taxi.GetCurrentTaxiPath();

    // search appropriate start path node
    uint32 startNode = 0;

    TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];

    float distPrev;
    float distNext =
        (nodeList[0]->x - GetPositionX())*(nodeList[0]->x - GetPositionX()) +
        (nodeList[0]->y - GetPositionY())*(nodeList[0]->y - GetPositionY()) +
        (nodeList[0]->z - GetPositionZ())*(nodeList[0]->z - GetPositionZ());

    for (uint32 i = 1; i < nodeList.size(); ++i)
    {
        TaxiPathNodeEntry const* node = nodeList[i];
        TaxiPathNodeEntry const* prevNode = nodeList[i - 1];

        // skip nodes at another map
        if (node->MapID != GetMapId())
            continue;

        distPrev = distNext;

        distNext =
            (node->x - GetPositionX()) * (node->x - GetPositionX()) +
            (node->y - GetPositionY()) * (node->y - GetPositionY()) +
            (node->z - GetPositionZ()) * (node->z - GetPositionZ());

        float distNodes =
            (node->x - prevNode->x) * (node->x - prevNode->x) +
            (node->y - prevNode->y) * (node->y - prevNode->y) +
            (node->z - prevNode->z) * (node->z - prevNode->z);

        if (distNext + distPrev < distNodes)
        {
            startNode = i;
            break;
        }
    }

    GetSession()->SendDoFlight(mountDisplayId, path, startNode);
}

void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask, uint32 unTimeMs)
{
    for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
        if (idSchoolMask & (1 << i))
            prohibited[i] = prohibited_struct(unTimeMs);

    WorldPacket data(SMSG_SPELL_COOLDOWN, 1 * 1024);
    ByteBuffer dataBuffer(1 * 1024);
    ObjectGuid playerGuid = GetGUID();

    uint32 counter = 0;
    uint32 curMsTime = getMSTime();

    for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
    {
        if (itr->second->state == PLAYERSPELL_REMOVED)
            continue;

        uint32 unSpellId = itr->first;
        SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(unSpellId);
        if (!spellInfo)
        {
            ASSERT(spellInfo);
            continue;
        }
        // Not send cooldown for this spells
        if (spellInfo->IsCooldownStartedOnEvent())
            continue;

        if ((spellInfo->PreventionType & (SpellPreventionMask::Silence)) == 0)
            continue;

        for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
        {
            if (idSchoolMask & (1 << i))
            {
                if (((1 << i) & spellInfo->GetSchoolMask()) && GetSpellCooldownDelay(unSpellId) < unTimeMs)
                {
                    SpellSchools school = GetFirstSchoolInMask(spellInfo->GetSchoolMask());
                    if ((1 << school) != spellInfo->GetSchoolMask())
                    {
                        SpellSchoolMask d_mask = SpellSchoolMask((1 << i) ^ spellInfo->GetSchoolMask());
                        bool do_break = false;
                        for (uint8 i = 0; i < MAX_SPELL_SCHOOL; ++i)
                        {
                            if (d_mask & (1 << i))
                            {
                                if (prohibited[i].m_time_prohibited_until < curMsTime)
                                {
                                    do_break = true;
                                    break;
                                }
                                else
                                {
                                    unTimeMs = std::max(unTimeMs, prohibited[i].m_time_prohibited_until - curMsTime);
                                }
                            }
                        }

                        if (do_break)
                            continue;
                    }
                    ++counter;
                    dataBuffer << uint32(unSpellId);
                    dataBuffer << uint32(unTimeMs);                       // in m.secs
                    AddSpellCooldown(unSpellId, 0, unTimeMs);
                }
            }
        }
    }

    data.appendPackGUID(playerGuid);
    data << uint8(1);
    data << uint32(counter);
    data.append(dataBuffer);

    GetSession()->SendPacket(&data);
}

void Player::InitDataForForm(bool reapplyMods)
{
    ShapeshiftForm form = GetShapeshiftForm();

    SpellShapeshiftFormEntry const* ssEntry = sSpellShapeshiftFormStore.LookupEntry(form);
    if (ssEntry && ssEntry->attackSpeed)
    {
        SetAttackTime(WeaponAttackType::BaseAttack, ssEntry->attackSpeed);
        SetAttackTime(WeaponAttackType::OffAttack, ssEntry->attackSpeed);
        SetAttackTime(WeaponAttackType::RangedAttack, BASE_ATTACK_TIME);
    }
    else
        SetRegularAttackTime();

    switch (form)
    {
        case FORM_FIERCE_TIGER:
        case FORM_STURDY_OX:
        case FORM_GHOUL:
        case FORM_CAT:
        {
            if (getPowerType() != POWER_ENERGY)
                setPowerType(POWER_ENERGY);
            break;
        }
        case FORM_BEAR:
        {
            if (getPowerType() != POWER_RAGE)
                setPowerType(POWER_RAGE);
            break;
        }
        case FORM_SPIRITED_CRANE:
        case FORM_WISE_SERPENT:
        {
            if (getPowerType() != POWER_MANA)
                setPowerType(POWER_MANA);
            break;
        }
        default:                                            // 0, for example
        {
            ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
            if (cEntry && cEntry->DisplayPower < MAX_POWERS && uint32(getPowerType()) != cEntry->DisplayPower)
                setPowerType(Powers(cEntry->DisplayPower));
            break;
        }
    }

    // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
    if (!reapplyMods)
        UpdateEquipSpellsAtFormChange();

    UpdateAttackPowerAndDamage();
    UpdateAttackPowerAndDamage(true);
}

void Player::InitDisplayIds()
{
    PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
    if (!info)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
        return;
    }

    uint8 gender = getGender();
    switch (gender)
    {
        case GENDER_FEMALE:
            SetDisplayId(info->displayId_f);
            SetNativeDisplayId(info->displayId_f);
            break;
        case GENDER_MALE:
            SetDisplayId(info->displayId_m);
            SetNativeDisplayId(info->displayId_m);
            break;
        default:
            sLog->outError(LOG_FILTER_PLAYER, "Invalid gender %u for player", gender);
            return;
    }
}

inline bool Player::_StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot, int64 price, ItemTemplate const* pProto, Creature* pVendor, VendorItem const* crItem, bool bStore)
{
    ItemPosCountVec vDest;
    uint16 uiDest = 0;
    InventoryResult msg = bStore ?
        CanStoreNewItem(bag, slot, vDest, item, count) :
        CanEquipNewItem(slot, uiDest, item, false);
    if (msg != EQUIP_ERR_OK)
    {
        SendEquipError(msg, NULL, NULL, item);
        return false;
    }


    if (crItem->ExtendedCost) // case for new honor system
    {
        ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
        for (int i = 0; i < MAX_ITEM_EXT_COST_CURRENCIES; ++i)
        {
            if (iece->RequiredItem[i])
                DestroyItemCount(iece->RequiredItem[i], iece->RequiredItemCount[i] * count, true);
        }

        for (int i = 0; i < MAX_ITEM_EXT_COST_CURRENCIES; ++i)
        {
            if (iece->RequiredCurrency[i])
                if (i != 1 || iece->ID == 2999) // 1 are season count request, we must not substract it
                    ModifyCurrency(iece->RequiredCurrency[i], -int32(iece->RequiredCurrencyCount[i] * count), true, true);
        }

        if (uint32 l_OverridePrice = iece->OverrideBuyPrice)
        {
            price = l_OverridePrice * count * GetReputationPriceDiscount(pVendor);

            if (int64 priceMod = int64(GetTotalAuraModifier(SPELL_AURA_MOD_VENDOR_ITEMS_PRICES)))
                price -= CalculatePct(price, priceMod);
        }
    }

    ModifyMoney(-price);

    Item* it = bStore ?
        StoreNewItem(vDest, item, true) :
        EquipNewItem(uiDest, item, true);
    if (it)
    {
        uint32 new_count = pVendor->UpdateVendorItemCurrentCount(crItem, count);

        WorldPacket data(SMSG_BUY_ITEM, 16 + 2 + 4 + 4 + 4);

        ObjectGuid vendorGuid = pVendor->GetGUID();

        data.appendPackGUID(vendorGuid);
        data << uint32(vendorslot + 1);                   // numbered from 1 at client
        data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
        data << uint32(count);

        GetSession()->SendPacket(&data);
        SendNewItem(it, count, true, false, false);

        if (!bStore)
            AutoUnequipOffhandIfNeed();

        if (pProto->Flags & ITEM_FLAG_REFUNDABLE && crItem->ExtendedCost && pProto->GetMaxStackSize() == 1)
        {
            it->SetFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE);
            it->SetUInt32Value(ITEM_FIELD_CONTEXT, 14);
            it->SetRefundRecipient(GetGUIDLow());
            it->SetPaidMoney(price);
            it->SetPaidExtendedCost(crItem->ExtendedCost);
            it->SaveRefundDataToDB();
            AddRefundReference(it->GetGUIDLow());
        }
    }
    return true;
}

bool Player::BuyCurrencyFromVendorSlot(uint64 vendorGuid, uint32 vendorSlot, uint32 currency, uint32 count)
{
    //vendorSlot += 1; Already handled in HandleBuyItemOpcode ?

    // cheating attempt
    if (count < 1) count = 1;

    if (!isAlive())
        return false;

    CurrencyTypesEntry const* proto = sCurrencyTypesStore.LookupEntry(currency);
    if (!proto)
    {
        SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, currency, 0);
        return false;
    }

    Creature* creature = GetNPCIfCanInteractWith(vendorGuid, UNIT_NPC_FLAG_VENDOR);
    if (!creature)
    {
        sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: BuyCurrencyFromVendorSlot - Unit (GUID: %u) not found or you can't interact with him.", GUID_LOPART(vendorGuid));
        SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, NULL, currency, 0);
        return false;
    }

    VendorItemData const* vItems = creature->GetVendorItems();
    if (!vItems || vItems->Empty())
    {
        SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, currency, 0);
        return false;
    }

    if (vendorSlot >= vItems->GetItemCount())
    {
        SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, currency, 0);
        return false;
    }

    VendorItem const* crItem = vItems->GetItem(vendorSlot);
    // store diff item (cheating)
    if (!crItem || crItem->item != currency || crItem->Type != ITEM_VENDOR_TYPE_CURRENCY)
    {
        SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, currency, 0);
        return false;
    }

    if (crItem->PlayerConditionID != 0 && EvalPlayerCondition(crItem->PlayerConditionID).first == false)
    {
        /// @TODO find the right error
        return false;
    }

    int32 precision = (proto->Flags & CURRENCY_FLAG_HIGH_PRECISION) ? CURRENCY_PRECISION : 1;

    if (crItem->ExtendedCost)
    {
        // Can only buy full stacks for extended cost
        if ((crItem->maxcount * precision) != count)
        {
            SendEquipError(EQUIP_ERR_CANT_BUY_QUANTITY, NULL, NULL);
            return false;
        }

        ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
        if (!iece)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Currency %u have wrong ExtendedCost field value %u", currency, crItem->ExtendedCost);
            return false;
        }

        for (uint8 i = 0; i < MAX_ITEM_EXT_COST_ITEMS; ++i)
        {
            if (iece->RequiredItem[i] && !HasItemCount(iece->RequiredItem[i], iece->RequiredItemCount[i] * count))
            {
                SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
                return false;
            }
        }

        for (uint8 i = 0; i < MAX_ITEM_EXT_COST_CURRENCIES; ++i)
        {
            if (!iece->RequiredCurrency[i])
                continue;

            CurrencyTypesEntry const* entry = sCurrencyTypesStore.LookupEntry(iece->RequiredCurrency[i]);
            if (!entry)
            {
                SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, currency, 0); // Find correct error
                return false;
            }

            if (!HasCurrency(iece->RequiredCurrency[i], iece->RequiredCurrencyCount[i] * count))
            {
                SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL); // Find correct error
                return false;
            }
        }

        // check for personal arena rating requirement
        if (GetMaxPersonalArenaRatingRequirement(iece->RequiredArenaSlot) < iece->RequiredPersonalArenaRating)
        {
            // probably not the proper equip err
            SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, NULL, NULL);
            return false;
        }
    }
    else // currencies have no price defined, can only be bought with ExtendedCost
    {
        SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, currency, 0);
        return false;
    }

    ModifyCurrency(currency, crItem->maxcount * precision, true, true);

    if (crItem->ExtendedCost)
    {
        ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
        for (int i = 0; i < MAX_ITEM_EXT_COST_CURRENCIES; ++i)
        {
            if (iece->RequiredItem[i])
                DestroyItemCount(iece->RequiredItem[i], iece->RequiredItemCount[i] * count, true);
        }

        for (int i = 0; i < MAX_ITEM_EXT_COST_CURRENCIES; ++i)
        {
            if (iece->RequiredCurrency[i])
                if (i != 1 || iece->ID == 2999) // 1 are season count request, we must not substract it
                    ModifyCurrency(iece->RequiredCurrency[i], -int32(iece->RequiredCurrencyCount[i] * count), true, true);
        }
    }

    return true;
}

// Return true is the bought item has a max count to force refresh of window by caller
bool Player::BuyItemFromVendorSlot(uint64 vendorguid, uint32 vendorslot, uint32 item, uint8 count, uint8 bag, uint8 slot)
{
    // cheating attempt
    if (count < 1)
        count = 1;

    // cheating attempt
    if (slot > MAX_BAG_SIZE && slot != NULL_SLOT)
        return false;

    if (!isAlive())
        return false;

    ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item);
    if (!pProto)
    {
        SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
        return false;
    }

    Creature* creature = GetNPCIfCanInteractWith(vendorguid, UNIT_NPC_FLAG_VENDOR);
    if (!creature)
    {
        sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)));
        SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
        return false;
    }

    VendorItemData const* vItems = creature->GetVendorItems();
    if (!vItems || vItems->Empty())
    {
        SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
        return false;
    }

    if (vendorslot >= vItems->GetItemCount())
    {
        SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
        return false;
    }

    VendorItem const* crItem = vItems->GetItem(vendorslot);
    // store diff item (cheating)
    if (!crItem || crItem->item != item)
    {
        SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
        return false;
    }

    // check current item amount if it limited
    if (crItem->maxcount != 0)
    {
        if (creature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count)
        {
            SendBuyError(BUY_ERR_ITEM_ALREADY_SOLD, creature, item, 0);
            return false;
        }
    }

    if (pProto->RequiredReputationFaction && (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank))
    {
        SendBuyError(BUY_ERR_REPUTATION_REQUIRE, creature, item, 0);
        return false;
    }

    if (crItem->PlayerConditionID != 0 && EvalPlayerCondition(crItem->PlayerConditionID).first == false)
    {
        /// @TODO find the right error
        return false;
    }

    uint64 price = 0;

    if (crItem->ExtendedCost)
    {
        // Can only buy full stacks for extended cost
        /*if (pProto->BuyCount != count)
        {
            SendEquipError(EQUIP_ERR_CANT_BUY_QUANTITY, NULL, NULL);
            return false;
        }*/

        ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
        if (!iece)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
            return false;
        }

        if (uint32 l_OverridePrice = iece->OverrideBuyPrice)
            price = l_OverridePrice;

        for (uint8 i = 0; i < MAX_ITEM_EXT_COST_ITEMS; ++i)
        {
            if (iece->RequiredItem[i] && !HasItemCount(iece->RequiredItem[i], iece->RequiredItemCount[i] * count))
            {
                SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
                return false;
            }
        }

        for (uint8 i = 0; i < MAX_ITEM_EXT_COST_CURRENCIES; ++i)
        {
            if (!iece->RequiredCurrency[i])
                continue;

            CurrencyTypesEntry const* entry = sCurrencyTypesStore.LookupEntry(iece->RequiredCurrency[i]);
            if (!entry)
            {
                SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
                return false;
            }

            uint32 precision = (entry->Flags & CURRENCY_FLAG_HIGH_PRECISION) ? CURRENCY_PRECISION : 1;

            // Second field in dbc is season count except two strange rows
            if (i == 1 && iece->ID != 2999)
            {
                if ((iece->RequiredCurrencyCount[i] * count / precision) > GetCurrencyOnSeason(iece->RequiredCurrency[i], false))
                {
                    SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
                    return false;
                }
            }
            else if (!HasCurrency(iece->RequiredCurrency[i], iece->RequiredCurrencyCount[i]  * count))
            {
                SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
                return false;
            }
        }

        // check for personal arena rating requirement
        if (GetMaxPersonalArenaRatingRequirement(iece->RequiredArenaSlot) < iece->RequiredPersonalArenaRating)
        {
            // probably not the proper equip err
            SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, NULL, NULL);
            return false;
        }
    }

    std::vector<GuildReward> const& rewards = sGuildMgr->GetGuildRewards();

    for (auto reward: rewards)
    {
        if (pProto->ItemId != reward.Entry)
            continue;

        Guild* guild = sGuildMgr->GetGuildById(this->GetGuildId());

        if (!guild)
        {
            SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
            return false;
        }

        if (reward.Standing)
            if (this->GetReputationRank(REP_GUILD) < reward.Standing)
            {
                SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
                return false;
            }

        if (reward.AchievementId)
            if (!guild->GetAchievementMgr().HasAchieved(reward.AchievementId))
            {
                if (!(reward.AchievementId == 5492 && guild->GetAchievementMgr().HasAchieved(4912)) && !(reward.AchievementId == 4912 && guild->GetAchievementMgr().HasAchieved(5492)))
                {
                    SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
                    return false;
                }
            }

        if (reward.Racemask)
            if (!(this->getRaceMask() & reward.Racemask))
            {
                SendBuyError(BUY_ERR_CANT_FIND_ITEM, creature, item, 0);
                return false;
            }
    }

    if (!price && crItem->IsGoldRequired(pProto) && pProto->BuyPrice > 0) //Assume price cannot be negative (do not know why it is int32)
    {
        uint32 maxCount = MAX_MONEY_AMOUNT / pProto->BuyPrice;
        if ((uint32)count > maxCount)
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player %s tried to buy %u item id %u, causing overflow", GetName(), (uint32)count, pProto->ItemId);
            count = (uint8)maxCount;
        }

        price = uint64(pProto->BuyPrice);
    }

    if (price)
    {
        price *= count; //it should not exceed MAX_MONEY_AMOUNT

        // reputation discount
        price = uint64(floor(price * GetReputationPriceDiscount(creature)));

        if (int64 priceMod = int64(GetTotalAuraModifier(SPELL_AURA_MOD_VENDOR_ITEMS_PRICES)))
            price -= CalculatePct(price, priceMod);

        if (!HasEnoughMoney(price))
        {
            SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, creature, item, 0);
            return false;
        }
    }

    if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
    {
        if (!_StoreOrEquipNewItem(vendorslot, item, count, bag, slot, price, pProto, creature, crItem, true))
            return false;
    }
    else if (IsEquipmentPos(bag, slot))
    {
        if (count != 1)
        {
            SendEquipError(EQUIP_ERR_NOT_EQUIPPABLE, NULL, NULL);
            return false;
        }
        if (!_StoreOrEquipNewItem(vendorslot, item, count, bag, slot, price, pProto, creature, crItem, false))
            return false;
    }
    else
    {
        SendEquipError(EQUIP_ERR_WRONG_SLOT, NULL, NULL);
        return false;
    }

    if (crItem->maxcount != 0) // bought
    {
        /*if (pProto->Quality > ITEM_QUALITY_EPIC || (pProto->Quality == ITEM_QUALITY_EPIC && pProto->ItemLevel >= MinNewsItemLevel[sWorld->getIntConfig(CONFIG_EXPANSION)]))
            if (Guild* guild = sGuildMgr->GetGuildById(GetGuildId()))
                guild->GetNewsLog().AddNewEvent(GUILD_NEWS_ITEM_PURCHASED, time(NULL), GetGUID(), 0, item);*/
        return true;
    }
    return false;
}

uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot) const
{
    // returns the maximal personal arena rating that can be used to purchase items requiring this condition
    // the personal rating of the arena team must match the required limit as well
    // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
    uint32 max_personal_rating = 0;
    for (uint8 i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
    {
        if (max_personal_rating < GetArenaPersonalRating(i))
            max_personal_rating = GetArenaPersonalRating(i);
    }
    return max_personal_rating;
}

void Player::UpdateHomebindTime(uint32 time)
{
    // GMs never get homebind timer online
    if (m_InstanceValid || isGameMaster() || IsInGarrison())
    {
        if (m_HomebindTimer)                                 // instance valid, but timer not reset
        {
            // hide reminder
            WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
            data << uint32(0);
            data << uint32(0);
            GetSession()->SendPacket(&data);
        }
        // instance is valid, reset homebind timer
        m_HomebindTimer = 0;
    }
    else if (m_HomebindTimer > 0)
    {
        if (time >= m_HomebindTimer)
        {
            // teleport to nearest graveyard
            RepopAtGraveyard();
        }
        else
            m_HomebindTimer -= time;
    }
    else
    {
        // instance is invalid, start homebind timer
        m_HomebindTimer = 60000;
        // send message to player
        WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
        data << uint32(m_HomebindTimer);
        data << uint32(1);
        GetSession()->SendPacket(&data);
        sLog->outDebug(LOG_FILTER_MAPS, "PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(), GetGUIDLow());
    }
}

void Player::UpdatePvPState(bool onlyFFA)
{
    // TODO: should we always synchronize UNIT_FIELD_BYTES_2, 1 of controller and controlled?
    // no, we shouldn't, those are checked for affecting player by client
    if (!pvpInfo.inNoPvPArea && !isGameMaster()
        && (pvpInfo.inFFAPvPArea || sWorld->IsFFAPvPRealm()))
    {
        if (!HasByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP))
        {
            SetByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP);
            for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
                (*itr)->SetByteValue(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP);
        }
    }
    else if (HasByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP))
    {
        RemoveByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP);
        for (ControlList::iterator itr = m_Controlled.begin(); itr != m_Controlled.end(); ++itr)
            (*itr)->RemoveByteFlag(UNIT_FIELD_SHAPESHIFT_FORM, 1, UNIT_BYTE2_FLAG_FFA_PVP);
    }

    if (onlyFFA)
        return;

    if (pvpInfo.inHostileArea)                               // in hostile area
    {
        if (!IsPvP() || pvpInfo.endTimer != 0)
            UpdatePvP(true, true);
    }
    else                                                    // in friendly area
    {
        if (IsPvP() && !HasFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
            pvpInfo.endTimer = time(0);                     // start toggle-off
    }
}

void Player::UpdatePvP(bool state, bool override)
{
    if (!state || override)
    {
        SetPvP(state);
        pvpInfo.endTimer = 0;
    }
    else
    {
        pvpInfo.endTimer = time(NULL);
        SetPvP(state);
    }
}

void Player::AddSpellAndCategoryCooldowns(SpellInfo const* p_SpellInfo, uint32 p_ItemId, Spell* p_Spell, bool p_InfinityCooldown)
{
    /// No need to set cooldown for Battle resurrection spells during a raid encounter
    /// Now we have a system using Battle resurrection charges
    if (p_SpellInfo->IsBattleResurrection())
    {
        if (InstanceScript* l_InstanceScript = GetInstanceScript())
        {
            if (l_InstanceScript->IsEncounterInProgress() && l_InstanceScript->instance->IsRaid())
                return;
        }
    }

    // init cooldown values
    uint32 l_CategoryId       = 0; // cat
    int64  l_Cooldown         = -1; //rec
    int64  l_CategoryCooldown = -1; //catrec

    // some special item spells without correct cooldown in SpellInfo
    // cooldown information stored in item prototype
    // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
    if (p_ItemId)
    {
        if (ItemTemplate const* l_Proto = sObjectMgr->GetItemTemplate(p_ItemId))
        {
            for (uint8 l_Idx = 0; l_Idx < MAX_ITEM_SPELLS; ++l_Idx)
            {
                if (uint32(l_Proto->Spells[l_Idx].SpellId) == p_SpellInfo->Id)
                {
                    l_CategoryId       = l_Proto->Spells[l_Idx].SpellCategory;
                    l_Cooldown         = l_Proto->Spells[l_Idx].SpellCooldown;
                    l_CategoryCooldown = l_Proto->Spells[l_Idx].SpellCategoryCooldown;
                    break;
                }
            }
        }
    }

    // if no cooldown found above then base at DBC data
    if (l_Cooldown < 0 && l_CategoryCooldown < 0)
    {
        l_CategoryId       = p_SpellInfo->GetCategory();
        l_Cooldown         = p_SpellInfo->RecoveryTime;
        l_CategoryCooldown = p_SpellInfo->CategoryRecoveryTime;
    }

    uint64 l_CurTime = 0;
    ACE_OS::gettimeofday().msec(l_CurTime);

    uint64 l_CooldownTime;
    uint64 l_CategoryCooldownTime;

    bool l_NeedsCooldownPacket = false;

    // overwrite time for selected category
    if (p_InfinityCooldown)
    {
        // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
        // but not allow ignore until reset or re-login
        l_CategoryCooldownTime = l_CategoryCooldown > 0 ? infinityCooldownDelay : 0;
        l_CooldownTime         = l_Cooldown         > 0 ? infinityCooldownDelay : l_CategoryCooldownTime;
    }
    else
    {
        // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
        // prevent 0 cooldowns set by another way
        if (l_Cooldown <= 0 && l_CategoryCooldown <= 0 && (l_CategoryId == 7611 || (p_SpellInfo->IsAutoRepeatRangedSpell() && p_SpellInfo->Id != 75 && p_SpellInfo->Id != 5019 && p_SpellInfo->Id != 121733)))
            l_Cooldown = GetAttackTime(WeaponAttackType::RangedAttack);

        // Now we have cooldown data (if found any), time to apply mods
        if (l_Cooldown > 0)
            ApplySpellMod(p_SpellInfo->Id, SPELLMOD_COOLDOWN, l_Cooldown, p_Spell);

        if (l_CategoryCooldown > 0 && !(p_SpellInfo->AttributesEx6 & SPELL_ATTR6_IGNORE_CATEGORY_COOLDOWN_MODS))
            ApplySpellMod(p_SpellInfo->Id, SPELLMOD_COOLDOWN, l_CategoryCooldown, p_Spell);

        if (int32 l_CooldownMod = GetTotalAuraModifier(SPELL_AURA_MOD_COOLDOWN))
        {
            // Apply SPELL_AURA_MOD_COOLDOWN only to own spells
            if (HasSpell(p_SpellInfo->Id))
            {
                l_NeedsCooldownPacket = true;
                l_Cooldown += l_CooldownMod * IN_MILLISECONDS;   // SPELL_AURA_MOD_COOLDOWN does not affect category cooldows, verified with shaman shocks
            }
        }

        if (int32 l_CooldownMod = GetTotalAuraModifier(SPELL_AURA_MOD_COOLDOWN_BY_HASTE))
        {
            float l_Haste = 1.0f - GetFloatValue(UNIT_FIELD_MOD_HASTE);

            if (l_Cooldown > 0)
                l_Cooldown -= CalculatePct(CalculatePct(l_Cooldown, (l_Haste * 100)), l_CooldownMod);

            if (l_CategoryCooldown > 0)
                l_CategoryCooldown -= CalculatePct(CalculatePct(l_CategoryCooldown, (l_Haste * 100)), l_CooldownMod);

            l_NeedsCooldownPacket = true;
        }

        AuraEffectList const& l_ListAuraCooldownByHaste = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_COOLDOWN_BY_HASTE);
        if (!l_ListAuraCooldownByHaste.empty())
        {
            float l_Haste = 1.0f - GetFloatValue(UNIT_FIELD_MOD_HASTE);

            for (AuraEffect* l_AuraEffect : l_ListAuraCooldownByHaste)
            {
                if (l_AuraEffect->IsAffectingSpell(p_SpellInfo))
                {
                    if (l_Cooldown > 0)
                        l_Cooldown -= CalculatePct(CalculatePct(l_Cooldown, (l_Haste * 100)), l_AuraEffect->GetAmount());

                    if (l_CategoryCooldown > 0)
                        l_CategoryCooldown -= CalculatePct(CalculatePct(l_CategoryCooldown, (l_Haste * 100)), l_AuraEffect->GetAmount());

                    l_NeedsCooldownPacket = true;
                }
            }
        }

        if (l_CategoryId)
        {
            if (int32 l_CategoryModifier = GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_SPELL_CATEGORY_COOLDOWN, l_CategoryId))
            {
                if (l_Cooldown > 0)
                    l_Cooldown += l_CategoryModifier;

                if (l_CategoryCooldown > 0)
                    l_CategoryCooldown += l_CategoryModifier;
            }

            SpellCategoryEntry const* l_CategoryEntry = sSpellCategoryStore.LookupEntry(l_CategoryId);
            if (l_CategoryEntry->Flags & SPELL_CATEGORY_FLAG_COOLDOWN_EXPIRES_AT_DAILY_RESET)
                l_CategoryCooldown = (sWorld->GetNextDailyQuestsResetTime() * IN_MILLISECONDS) - l_CurTime;
        }

        // replace negative cooldowns by 0
        if (l_Cooldown < 0)
            l_Cooldown = 0;

        if (l_CategoryCooldown < 0)
            l_CategoryCooldown = 0;

        // no cooldown after applying spell mods
        if (l_Cooldown == 0 && l_CategoryCooldown == 0)
            return;

        l_CategoryCooldownTime = l_CategoryCooldown ? l_CategoryCooldown : 0;
        l_CooldownTime = l_Cooldown ? l_Cooldown : l_CategoryCooldownTime;
    }

    // self spell cooldown
    if (l_CooldownTime > 0)
        AddSpellCooldown(p_SpellInfo->Id, p_ItemId, l_CooldownTime, l_NeedsCooldownPacket);
}

void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, uint64 end_time, bool p_send /* = false */)
{
    uint64 curTime = 0;
    ACE_OS::gettimeofday().msec(curTime);

    SpellCooldown sc;
    sc.end = curTime + end_time;
    sc.itemid = itemid;
    m_spellCooldowns[spellid] = sc;

    if (p_send)
    {
        WorldPacket data(SMSG_SPELL_COOLDOWN, 16 + 2 + 1 + 4 + 4 + 4);
        data.appendPackGUID(GetGUID());
        data << uint8(CooldownFlags::CooldownFlagNone);
        data << uint32(1);
        data << uint32(spellid);
        data << uint32(end_time);

        GetSession()->SendPacket(&data);
    }
}

void Player::SendCategoryCooldown(uint32 p_CategoryID, int32 p_CoolDown)
{
    WorldPacket l_Packet(SMSG_CATEGORY_COOLDOWN, 16 + 2 + 1 + 4 + 4 + 4);
    l_Packet << uint32(1);
    l_Packet << uint32(p_CategoryID);
    l_Packet << uint32(p_CoolDown);
    SendDirectMessage(&l_Packet);
}

void Player::SendCooldownEvent(const SpellInfo * p_SpellInfo, uint32 p_ItemID, Spell * p_Spell, bool p_SetCooldown)
{
    /// start cooldowns at server side, if any
    if (p_SetCooldown)
        AddSpellAndCategoryCooldowns(p_SpellInfo, p_ItemID, p_Spell);

    /// Send activate cooldown timer (possible 0) at client side
    WorldPacket l_Data(SMSG_COOLDOWN_EVENT, 4 + 8);
    l_Data << uint32(p_SpellInfo->Id);
    l_Data.WriteBit(false);             ///< IsPet

    SendDirectMessage(&l_Data);
}

void Player::UpdatePotionCooldown(Spell* spell)
{
    // no potion used in combat or still in combat
    if (!m_lastPotionId || isInCombat())
        return;

    // Call not from spell cast, send cooldown event for item spells if no in combat
    if (!spell)
    {
        // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
        if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(m_lastPotionId))
            for (uint8 idx = 0; idx < MAX_ITEM_PROTO_SPELLS; ++idx)
                if (proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
                    if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(proto->Spells[idx].SpellId))
                            SendCooldownEvent(spellInfo, m_lastPotionId);
    }
    // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
    else
        SendCooldownEvent(spell->m_spellInfo, m_lastPotionId, spell);

    m_lastPotionId = 0;
}
                                                           //slot to be excluded while counting
bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
{
    if (!enchantmentcondition)
        return true;

    SpellItemEnchantmentConditionEntry const* Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);

    if (!Condition)
        return true;

    uint8 curcount[4] = {0, 0, 0, 0};

    //counting current equipped gem colors
    for (uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        if (i == slot)
            continue;
        Item* pItem2 = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
        if (pItem2 && !pItem2->CantBeUse() && pItem2->GetTemplate()->Socket[0].Color)
        {
            for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
            {
                uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
                if (!enchant_id)
                    continue;

                SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
                if (!enchantEntry)
                    continue;

                uint32 gemid = enchantEntry->GemID;
                if (!gemid)
                    continue;

                ItemTemplate const* gemProto = sObjectMgr->GetItemTemplate(gemid);
                if (!gemProto)
                    continue;

                GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
                if (!gemProperty)
                    continue;

                uint8 GemColor = gemProperty->color;

                for (uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
                {
                    if (tmpcolormask & GemColor)
                        ++curcount[b];
                }
            }
        }
    }

    bool activate = true;

    for (uint8 i = 0; i < 5; i++)
    {
        if (!Condition->Color[i])
            continue;

        uint32 _cur_gem = curcount[Condition->Color[i] - 1];

        if ((Condition->CompareColor[i] - 1) > 3)
            continue;

        // if have <CompareColor> use them as count, else use <value> from Condition
        uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];

        switch (Condition->Comparator[i])
        {
            case 2:                                         // requires less <color> than (<value> || <comparecolor>) gems
                activate &= (_cur_gem < _cmp_gem) ? true : false;
                break;
            case 3:                                         // requires more <color> than (<value> || <comparecolor>) gems
                activate &= (_cur_gem > _cmp_gem) ? true : false;
                break;
            case 5:                                         // requires at least <color> than (<value> || <comparecolor>) gems
                activate &= (_cur_gem >= _cmp_gem) ? true : false;
                break;
        }
    }

    sLog->outDebug(LOG_FILTER_PLAYER_ITEMS, "Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no");

    return activate;
}

void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
{
                                                            //cycle all equipped items
    for (uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
    {
        //enchants for the slot being socketed are handled by Player::ApplyItemMods
        if (slot == exceptslot)
            continue;

        Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);

        if (!pItem || !pItem->GetTemplate()->Socket[0].Color)
            continue;

        for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
        {
            uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
            if (!enchant_id)
                continue;

            SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
            if (!enchantEntry)
                continue;

            uint32 condition = enchantEntry->EnchantmentCondition;
            if (condition)
            {
                                                            //was enchant active with/without item?
                bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
                                                            //should it now be?
                if (wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
                {
                    // ignore item gem conditions
                    //if state changed, (dis)apply enchant
                    ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
                }
            }
        }
    }
}

void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
{
    //cycle all equipped items
    for (int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
    {
        //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recvData)
        if (slot == exceptslot)
            continue;

        Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);

        if (!pItem || !pItem->GetTemplate()->Socket[0].Color)   //if item has no sockets or no item is equipped go to next item
            continue;

        //cycle all (gem)enchants
        for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
        {
            uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
            if (!enchant_id)                                 //if no enchant go to next enchant(slot)
                continue;

            SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
            if (!enchantEntry)
                continue;

            //only metagems to be (de)activated, so only enchants with condition
            uint32 condition = enchantEntry->EnchantmentCondition;
            if (condition)
                ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), apply);
        }
    }
}

void Player::SetBattlegroundEntryPoint()
{
    // Taxi path store
    if (!m_taxi.IsPathEmpty())
    {
        m_bgData.mountSpell  = 0;
        m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
        m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();

        // On taxi we don't need check for dungeon
        m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
    }
    else
    {
        m_bgData.ClearTaxiPath();

        // Mount spell id storing
        if (IsMounted())
        {
            AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOUNTED);
            if (!auras.empty())
                m_bgData.mountSpell = (*auras.begin())->GetId();
        }
        else
            m_bgData.mountSpell = 0;

        if (Aura* aur = GetAura(33943))
            m_bgData.mountSpell = 33943;

        // If map is dungeon find linked graveyard
        if (GetMap()->IsDungeon() && !IsInGarrison())
        {
            if (const WorldSafeLocsEntry* entry = sObjectMgr->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
                m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
            else
                sLog->outError(LOG_FILTER_PLAYER, "SetBattlegroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
        }
        // If new entry point is not BG or arena set it
        else if (!GetMap()->IsBattlegroundOrArena())
            m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
    }

    if (m_bgData.joinPos.m_mapId == MAPID_INVALID) // In error cases use homebind position
        m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
}

void Player::LeaveBattleground(bool teleportToEntryPoint)
{
    if (Battleground* bg = GetBattleground())
    {
        bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);

        // call after remove to be sure that player resurrected for correct cast
        if (bg->isBattleground() && !isGameMaster() && sWorld->getBoolConfig(CONFIG_BATTLEGROUND_CAST_DESERTER))
        {
            if (bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN)
            {
                //lets check if player was teleported from BG and schedule delayed Deserter spell cast
                if (IsBeingTeleportedFar())
                {
                    ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
                    return;
                }

                CastSpell(this, 26013, true); ///< Deserter
            }
        }
        sScriptMgr->OnLeaveBG(this, bg->GetMapId());
    }
}

bool Player::CanJoinToBattleground() const
{
    /// Check Deserter debuff.
    if (HasAura(MS::Battlegrounds::Spells::DeserterBuff))
        return false;

    return true;
}

bool Player::CanReportAfkDueToLimit()
{
    // a player can complain about 15 people per 5 minutes
    if (m_bgData.bgAfkReportedCount++ >= 15)
        return false;

    return true;
}

///This player has been blamed to be inactive in a battleground
void Player::ReportedAfkBy(Player* reporter)
{
    Battleground* bg = GetBattleground();
    // Battleground also must be in progress!
    if (!bg || bg != reporter->GetBattleground() || GetTeam() != reporter->GetTeam() || bg->GetStatus() != STATUS_IN_PROGRESS)
        return;

    // check if player has 'Idle' or 'Inactive' debuff
    if (m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680) && !HasAura(43681) && reporter->CanReportAfkDueToLimit())
    {
        m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
        // 5 players have to complain to apply debuff
        if (m_bgData.bgAfkReporter.size() >= 5)
        {
            // cast 'Idle' spell
            //CastSpell(this, 43680, true);
            m_bgData.bgAfkReporter.clear();
            LeaveBattleground();
        }
    }
}

WorldLocation Player::GetStartPosition() const
{
    PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
    uint32 mapId = info->mapId;
    if (getClass() == CLASS_DEATH_KNIGHT && HasSpell(50977))
        mapId = 0;
    return WorldLocation(mapId, info->positionX, info->positionY, info->positionZ, 0);
}

WorldLocation Player::GetPreviousLocation() const
{
    return WorldLocation(m_PreviousLocationMapId, m_PreviousLocationX, m_PreviousLocationY, m_PreviousLocationZ, m_PreviousLocationO);
}

bool Player::IsNeverVisible() const
{
    if (Unit::IsNeverVisible())
        return true;

    if (GetSession()->PlayerLogout() || GetSession()->PlayerLoading())
        return true;

    return false;
}

bool Player::CanAlwaysSee(WorldObject const* obj) const
{
    // Always can see self
    if (m_mover == obj)
        return true;

    if (uint64 guid = GetGuidValue(PLAYER_FIELD_FARSIGHT_OBJECT))
        if (obj->GetGUID() == guid)
            return true;

    return false;
}

bool Player::IsAlwaysDetectableFor(WorldObject const* seer) const
{
    if (Unit::IsAlwaysDetectableFor(seer))
        return true;

    if (const Player* seerPlayer = seer->ToPlayer())
        if (IsGroupVisibleFor(seerPlayer))
            return !(seerPlayer->m_Duel && seerPlayer->m_Duel->startTime != 0 && seerPlayer->m_Duel->opponent == this);

     return false;
 }

bool Player::IsVisibleGloballyFor(Player* u) const
{
    if (!u)
        return false;

    // Always can see self
    if (u == this)
        return true;

    // Visible units, always are visible for all players
    if (IsVisible())
        return true;

    // GMs are visible for higher gms (or players are visible for gms)
    if (!AccountMgr::IsPlayerAccount(u->GetSession()->GetSecurity()))
        return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();

    // non faction visibility non-breakable for non-GMs
    if (!IsVisible())
        return false;

    // non-gm stealth/invisibility not hide from global player lists
    return true;
}

template<class T>
inline void UpdateVisibilityOf_helper(GuidUnorderedSet& s64, T* target, std::set<Unit*>& /*v*/)
{
    s64.insert(target->GetGUID());
}

template<>
inline void UpdateVisibilityOf_helper(GuidUnorderedSet& s64, GameObject* target, std::set<Unit*>& /*v*/)
{
    // But exclude stoppable elevators from this hack - they would be teleporting from one end to another
    // if affected transports move so far horizontally that it causes them to run out of visibility range then you are out of luck
    // fix visibility instead of adding hacks here
    if (!target->IsTransport())
        s64.insert(target->GetGUID());
}

template<>
inline void UpdateVisibilityOf_helper(GuidUnorderedSet& s64, Creature* target, std::set<Unit*>& v)
{
    s64.insert(target->GetGUID());
    v.insert(target);
}

template<>
inline void UpdateVisibilityOf_helper(GuidUnorderedSet& s64, Player* target, std::set<Unit*>& v)
{
    s64.insert(target->GetGUID());
    v.insert(target);
}

template<class T>
inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
{
}

template<>
inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
{
    if (p->GetPetGUID() == t->GetGUID() && t->ToCreature()->isPet())
        t->ToPet()->Remove(PET_SLOT_OTHER_PET, true, t->ToPet()->m_Stampeded);
}

void Player::UpdateVisibilityOf(WorldObject* target)
{
    if (HaveAtClient(target))
    {
        if (!canSeeOrDetect(target, false, true))
        {
            if (target->GetTypeId() == TYPEID_UNIT)
                BeforeVisibilityDestroy<Creature>(target->ToCreature(), this);

            target->DestroyForPlayer(this);
            m_clientGUIDs.erase(target->GetGUID());
            m_VignetteMgr.OnWorldObjectDisappear(target);

            #ifdef TRINITY_DEBUG
                sLog->outDebug(LOG_FILTER_MAPS, "Object %u (Type: %u) out of range for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), GetGUIDLow(), GetDistance(target));
            #endif
        }
    }
    else
    {
        if (canSeeOrDetect(target, false, true))
        {
            target->SendUpdateToPlayer(this);
            m_clientGUIDs.insert(target->GetGUID());
            m_VignetteMgr.OnWorldObjectAppear(target);

            #ifdef TRINITY_DEBUG
                sLog->outDebug(LOG_FILTER_MAPS, "Object %u (Type: %u) is visible now for player %u. Distance = %f", target->GetGUIDLow(), target->GetTypeId(), GetGUIDLow(), GetDistance(target));
            #endif

            // target aura duration for caster show only if target exist at caster client
            // send data at target visibility change (adding to client)
            if (target->isType(TYPEMASK_UNIT))
                SendInitialVisiblePackets((Unit*)target);
        }
    }
}

void Player::UpdateTriggerVisibility()
{
    if (m_clientGUIDs.empty())
        return;

    if (!IsInWorld())
        return;

    UpdateData udata(GetMapId());
    WorldPacket packet;
    for (auto itr = m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
    {
        if (IS_CREATURE_GUID(*itr))
        {
            Creature* obj = GetMap()->GetCreature(*itr);
            if (!obj || (!obj->isTrigger() && !obj->HasAuraType(SPELL_AURA_TRANSFORM) && !obj->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)))
                continue;

            obj->SetFieldNotifyFlag(UF_FLAG_PUBLIC);
            obj->BuildValuesUpdateBlockForPlayer(&udata, this);
            obj->RemoveFieldNotifyFlag(UF_FLAG_PUBLIC);
        }
        else if (IS_GAMEOBJECT_GUID((*itr)))
        {
            GameObject* go = GetMap()->GetGameObject(*itr);
            if (!go)
                continue;

            go->SetFieldNotifyFlag(UF_FLAG_PUBLIC);
            go->BuildValuesUpdateBlockForPlayer(&udata, this);
            go->RemoveFieldNotifyFlag(UF_FLAG_PUBLIC);
        }
    }
    if (!udata.HasData())
        return;

    if (udata.BuildPacket(&packet))
        GetSession()->SendPacket(&packet);
}

void Player::SendInitialVisiblePackets(Unit* p_Target)
{
    SendAurasForTarget(p_Target);

    if (p_Target->isAlive())
    {
        if (p_Target->HasUnitState(UNIT_STATE_MELEE_ATTACKING) && p_Target->getVictim())
            p_Target->SendMeleeAttackStart(p_Target->getVictim());
    }
}

template<class T>
void Player::UpdateVisibilityOf(T* p_Target, UpdateData& p_UpdData, std::set<Unit*>& p_VisibleNow)
{
    if (HaveAtClient(p_Target))
    {
        if (!canSeeOrDetect(p_Target, false, true))
        {
            BeforeVisibilityDestroy<T>(p_Target, this);

            p_Target->BuildOutOfRangeUpdateBlock(&p_UpdData);
            m_clientGUIDs.erase(p_Target->GetGUID());
            m_VignetteMgr.OnWorldObjectDisappear(p_Target);

            #ifdef TRINITY_DEBUG
                sLog->outDebug(LOG_FILTER_MAPS, "Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f", p_Target->GetGUIDLow(), p_Target->GetTypeId(), p_Target->GetEntry(), GetGUIDLow(), GetDistance(p_Target));
            #endif
        }
    }
    else
    {
        if (canSeeOrDetect(p_Target, false, true))
        {
            p_Target->BuildCreateUpdateBlockForPlayer(&p_UpdData, this);
            UpdateVisibilityOf_helper(m_clientGUIDs, p_Target, p_VisibleNow);
            m_VignetteMgr.OnWorldObjectAppear(p_Target);

            #ifdef TRINITY_DEBUG
                sLog->outDebug(LOG_FILTER_MAPS, "Object %u (Type: %u, Entry: %u) is visible now for player %u. Distance = %f", p_Target->GetGUIDLow(), p_Target->GetTypeId(), p_Target->GetEntry(), GetGUIDLow(), GetDistance(p_Target));
            #endif
        }
    }
}

template void Player::UpdateVisibilityOf(Player*        target, UpdateData& data, std::set<Unit*>& visibleNow);
template void Player::UpdateVisibilityOf(Creature*      target, UpdateData& data, std::set<Unit*>& visibleNow);
template void Player::UpdateVisibilityOf(Corpse*        target, UpdateData& data, std::set<Unit*>& visibleNow);
template void Player::UpdateVisibilityOf(GameObject*    target, UpdateData& data, std::set<Unit*>& visibleNow);
template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, std::set<Unit*>& visibleNow);

void Player::UpdateVisibilityForPlayer()
{
    // updates visibility of all objects around point of view for current player
    JadeCore::VisibleNotifier notifier(*this);
    m_seer->VisitNearbyObject(GetSightRange(), notifier, true);
    notifier.SendToSelf();   // send gathered data
}

void Player::InitPrimaryProfessions()
{
    SetFreePrimaryProfessions(sWorld->getIntConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
}

void Player::ModifyMoney(int64 d)
{
    sScriptMgr->OnPlayerMoneyChanged(this, d);

    if (d < 0)
        SetMoney (GetMoney() > uint64(-d) ? GetMoney() + d : 0);
    else
    {
        uint64 newAmount = 0;
        if (GetMoney() < uint64(MAX_MONEY_AMOUNT - d))
            newAmount = GetMoney() + d;
        else
        {
            // "At Gold Limit"
            newAmount = MAX_MONEY_AMOUNT;
            if (d)
                SendEquipError(EQUIP_ERR_TOO_MUCH_GOLD, NULL, NULL);
        }
        SetMoney(newAmount);
    }
}

Unit* Player::GetSelectedUnit() const
{
    if (m_curSelection)
        return ObjectAccessor::GetUnit(*this, m_curSelection);
    return NULL;
}

Player* Player::GetSelectedPlayer() const
{
    if (m_curSelection)
        return ObjectAccessor::GetPlayer(*this, m_curSelection);
    return NULL;
}

void Player::SetGroup(Group* group, int8 subgroup)
{
    if (group == NULL)
        m_group.unlink();
    else
    {
        // never use SetGroup without a subgroup unless you specify NULL for group
        ASSERT(subgroup >= 0);
        m_group.link(group, this);
        m_group.setSubGroup((uint8)subgroup);
    }

    UpdateObjectVisibility(false);
}

void Player::SendInitialPacketsBeforeAddToMap()
{
    /// Pass 'this' as argument because we're not stored in ObjectAccessor yet
    GetSocial()->SendSocialList(this);

    // Guild bank list wtf?

    // Homebind
    WorldPacket l_Data(SMSG_BIND_POINT_UPDATE, 5 * 4);
    l_Data << m_homebindX << m_homebindY << m_homebindZ;
    l_Data << uint32(m_homebindMapId);
    l_Data << uint32(m_homebindAreaId);
    GetSession()->SendPacket(&l_Data);

    // SMSG_SET_PROFICIENCY
    // SMSG_SET_PCT_SPELL_MODIFIER
    // SMSG_SET_FLAT_SPELL_MODIFIER
    // SMSG_UPDATE_AURA_DURATION

    SendTalentsInfoData(false);

    SendKnownSpells();

    //4374 - summon pet spell in packet - 111896, 111895, 111859, 111897, 111898
    //5376

    SendInitialActionButtons();
    m_reputationMgr.SendInitialReputations();
    m_achievementMgr.SendAllAchievementData(this);

    SendEquipmentSetList();

    l_Data.Initialize(SMSG_LOGIN_SET_TIME_SPEED, 4 * 5);
    l_Data << uint32(MS::Utilities::WowTime::Encode(sWorld->GetGameTime())); // server hour    ServerTime
    l_Data << uint32(MS::Utilities::WowTime::Encode(sWorld->GetGameTime())); // local hour     GameTime
    l_Data << float(0.01666667f);                                 // game speed     NewSpeed
    l_Data << uint32(1);                                          // added in 5.4.0 GameTimeHolidayOffset or ServerTimeHolidayOffset
    l_Data << uint32(1);                                          // added in 3.1.2 GameTimeHolidayOffset or ServerTimeHolidayOffset
    GetSession()->SendPacket(&l_Data);

    bool l_IsInInstance = GetMap()->GetMapDifficulty() ? GetMap()->GetMapDifficulty()->MaxPlayers : false;

    l_Data.Initialize(SMSG_WORLD_SERVER_INFO, 4 * 5);
    l_Data << uint32(GetMap()->GetDifficultyID());                            ///< DifficultyID
    l_Data << uint8(0);                                                       ///< Is Tournament Realm
    l_Data << uint32(sWorld->GetNextWeeklyQuestsResetTime() - (2 * WEEK));    ///< Last Weekly Reset
    l_Data.WriteBit(false);                                                   ///< Has Restricted Account Max Level
    l_Data.WriteBit(false);                                                   ///< Has Restricted Account Max Money
    l_Data.WriteBit(false);                                                   ///< Has Ineligible For Loot Mask
    l_Data.WriteBit(l_IsInInstance);                                          ///< Has Instance Group Size

    if (l_IsInInstance)
        l_Data << uint32(GetMap()->GetPlayers().getSize());

    GetSession()->SendPacket(&l_Data);

    l_Data.Initialize(SMSG_INITIAL_SETUP, 2062);
    l_Data << uint8(sWorld->getIntConfig(CONFIG_EXPANSION));      ///< Server Expansion Level
    l_Data << uint8(0);                                           ///< Server Expansion Tier
    l_Data << uint32(sWorld->GetServerRegionID());                ///< Server Region ID
    l_Data << uint32(sWorld->GetServerRaidOrigin());              ///< Raid origin
    GetSession()->SendPacket(&l_Data);

    if (Pet* l_Pet = GetPet())
    {
        l_Data.Initialize(SMSG_PET_GUIDS);
        l_Data << uint32(1);
        l_Data.appendPackGUID(l_Pet->GetGUID());
        GetSession()->SendPacket(&l_Data);
    }

    // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
    // SMSG_UPDATE_WORLD_STATE
    // SMSG_POWER_UPDATE

    SendCurrencies();
    SetMover(this);

    /// Unlock WoD heroic dungeons
    if (uint32 l_QuestBit = GetQuestUniqueBitFlag(37213))   ///< FLAG - Proving Grounds - Damage Silver
        SetQuestBit(l_QuestBit, true);
    if (uint32 l_QuestBit = GetQuestUniqueBitFlag(33090))   ///< FLAG - Proving Grounds - Damage Silver
        SetQuestBit(l_QuestBit, true);
    if (uint32 l_QuestBit = GetQuestUniqueBitFlag(33096))   ///< FLAG - Proving Grounds - Healer Silver
        SetQuestBit(l_QuestBit, true);
    if (uint32 l_QuestBit = GetQuestUniqueBitFlag(37219))   ///< FLAG - Proving Grounds - Healer Silver
        SetQuestBit(l_QuestBit, true);
    if (uint32 l_QuestBit = GetQuestUniqueBitFlag(37216))   ///< FLAG - Proving Grounds - Tank Silver
        SetQuestBit(l_QuestBit, true);
    if (uint32 l_QuestBit = GetQuestUniqueBitFlag(33093))   ///< FLAG - Proving Grounds - Tank Silver
        SetQuestBit(l_QuestBit, true);
}

void Player::SendSpellHistory()
{
    uint64 l_CurTime = 0;
    ACE_OS::gettimeofday().msec(l_CurTime);

    WorldPacket l_HistoryData(SMSG_SEND_SPELL_HISTORY, 2 * 1024);
    l_HistoryData << uint32(GetSpellCooldownMap().size());

    for (SpellCooldowns::const_iterator l_Itr = GetSpellCooldownMap().begin(); l_Itr != GetSpellCooldownMap().end(); ++l_Itr)
    {
        l_HistoryData << uint32(l_Itr->first);
        l_HistoryData << uint32(l_Itr->second.itemid);

        bool l_HasCooldown = l_Itr->second.end > l_CurTime;

        uint32 l_Category             = 0;
        uint32 l_CategoryRecoveryTime = 0;
        uint32 l_RecoveryTime         = l_Itr->second.end - l_CurTime;

        if (ItemTemplate const* l_ItemProto = sObjectMgr->GetItemTemplate(l_Itr->second.itemid))
        {
            for (uint8 l_I = 0; l_I < MAX_ITEM_SPELLS; ++l_I)
            {
                if (uint32(l_ItemProto->Spells[l_I].SpellId) == l_Itr->first)
                {
                    l_Category             = l_ItemProto->Spells[l_I].SpellCategory;
                    l_CategoryRecoveryTime = l_ItemProto->Spells[l_I].SpellCategoryCooldown;
                    break;
                }
            }
        }

        l_HistoryData << uint32(l_Category);
        l_HistoryData << uint32(l_HasCooldown ? l_RecoveryTime : 0);
        l_HistoryData << uint32(l_CategoryRecoveryTime);

        l_HistoryData.FlushBits();

        l_HistoryData.WriteBit(false);  ///< OnHold
    }

    GetSession()->SendPacket(&l_HistoryData);
}

void Player::SendInitialPacketsAfterAddToMap()
{
    UpdateVisibilityForPlayer();

    // update zone
    uint32 newzone, newarea;
    GetZoneAndAreaId(newzone, newarea, true);
    UpdateZone(newzone, newarea);                            // also call SendInitWorldStates();

    ResetTimeSync();
    SendTimeSync();

    CastSpell(this, 836, true);                             // LOGINEFFECT

    // set some aura effects that send packet to player client after add player to map
    // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
    // same auras state lost at far teleport, send it one more time in this case also
    static const AuraType auratypes[] =
    {
        SPELL_AURA_MOD_FEAR,     SPELL_AURA_TRANSFORM,                 SPELL_AURA_WATER_WALK,
        SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER,                     SPELL_AURA_SAFE_FALL,
        SPELL_AURA_FLY,          SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED, SPELL_AURA_NONE
    };
    for (AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
    {
        Unit::AuraEffectList const& auraList = GetAuraEffectsByType(*itr);
        if (!auraList.empty())
            auraList.front()->HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true);
    }

    SendRefreshSpellMods();

    RemoveAllMovementForces();

    if (HasAuraType(SPELL_AURA_MOD_STUN))
        SetRooted(true);

    // manual send package (have code in HandleEffect(this, AURA_EFFECT_HANDLE_SEND_FOR_CLIENT, true); that must not be re-applied.
    if (HasAuraType(SPELL_AURA_MOD_ROOT) || HasAuraType(SPELL_AURA_MOD_ROOT_2))
        SendMoveRoot(0);

    SendSpellHistory();
    SendSpellCharges();
    SendAurasForTarget(this);
    SendEnchantmentDurations();                             // must be after add to map
    SendItemDurations();                                    // must be after add to map

    CutOffItemLevel(false);
    RescaleAllItemsIfNeeded(true);

    ApplyWargameItemModifications();

    AuraEffectList const& l_ModSpeedAuras = GetAuraEffectsByType(SPELL_AURA_MOD_SPEED_ALWAYS);
    for (AuraEffectList::const_iterator iter = l_ModSpeedAuras.begin(); iter != l_ModSpeedAuras.end(); ++iter)
        (*iter)->RecalculateAmount((*iter)->GetCaster(), true);

    if (GetMap()->IsRaid())
    {
        m_PrevMapDifficulty = GetMap()->GetDifficultyID();
        if (DifficultyEntry const* l_Difficulty = sDifficultyStore.LookupEntry(m_PrevMapDifficulty))
            SendRaidDifficulty((l_Difficulty->Flags & DIFFICULTY_FLAG_LEGACY) != 0, m_PrevMapDifficulty);
    }
    else if (GetMap()->IsNonRaidDungeon())
    {
        m_PrevMapDifficulty = GetMap()->GetDifficultyID();
        SendDungeonDifficulty(m_PrevMapDifficulty);
    }
    else if (!GetMap()->Instanceable())
    {
        if (DifficultyEntry const* l_Difficulty = sDifficultyStore.LookupEntry(m_PrevMapDifficulty))
            SendRaidDifficulty((l_Difficulty->Flags & DIFFICULTY_FLAG_LEGACY) != 0);
    }

    GetSession()->SendBattlePetJournal();

    if (GetSkillValue(SKILL_ARCHAEOLOGY))
    {
        m_archaeologyMgr.PropagateResearchSites();
        m_archaeologyMgr.PropagateResearchProjects();
    }

    SendDeathRuneUpdate();

    if (getClass() == CLASS_HUNTER)
        GetSession()->SendStablePet(0);

    // Hack fix for remove flags auras after crash
    if (!GetMap()->IsBattlegroundOrArena())
        RemoveFlagsAuras();

    // Hack fix for AURA_STATE_PVP_PREPARATION.
    if (GetBattleground() && GetBattleground()->GetStatus() == BattlegroundStatus::STATUS_WAIT_JOIN)
        ModifyAuraState(AURA_STATE_PVP_RAID_PREPARE, true);

    /// Fix ghost group leader flag
    if (!GetGroup() || !GetGroup()->IsLeader(GetGUID()))
        RemoveFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_GROUP_LEADER);

    WorldPacket l_NullPacket;
    GetSession()->HandleLfgGetStatus(l_NullPacket);

    /// Force map shift update
    if ((GetMapId() == MS::Garrison::Globals::BaseMap && m_Garrison) || IsInGarrison())
    {
        phaseMgr.Update();
        phaseMgr.ForceMapShiftUpdate();
    }

    if (IsInGarrison())
        m_Garrison->OnPlayerEnter();

    std::map<uint32, bool> l_MountSpells;
    for (PlayerSpellMap::iterator l_It = m_spells.begin(); l_It != m_spells.end(); ++l_It)
    {
        if (!l_It->second)
            continue;

        if (const SpellInfo * spell = sSpellMgr->GetSpellInfo(l_It->first))
        {
            if (spell->IsAbilityOfSkillType(SKILL_MOUNT) || spell->AttributesEx10 & SPELL_ATTR10_MOUNT_IS_NOT_ACCOUNT_WIDE)
            {
                l_MountSpells[l_It->first] = l_It->second->IsMountFavorite;
            }
        }
    }

    WorldPacket l_Data(SMSG_ACCOUNT_MOUNT_UPDATE, 2 * 1024);
    l_Data.WriteBit(true);                      ///< Is full update
    l_Data.FlushBits();
    l_Data << uint32(l_MountSpells.size());
    l_Data << uint32(l_MountSpells.size());

    for (auto l_Pair : l_MountSpells)
        l_Data << uint32(l_Pair.first);

    for (auto l_Pair : l_MountSpells)
        l_Data.WriteBit(l_Pair.second);

    l_Data.FlushBits();

    SendDirectMessage(&l_Data);
    GetSession()->SendTwitterStatus(true);

     if (Group* l_Group = GetGroup())
         l_Group->SendUpdate();

     sLFGListMgr->OnPlayerLogin(this);
}

void Player::SendUpdateToOutOfRangeGroupMembers()
{
    if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
        return;
    if (Group* group = GetGroup())
        group->UpdatePlayerOutOfRange(this);

    m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
    m_auraRaidUpdateMask = 0;
    if (Pet* pet = GetPet())
        pet->ResetAuraUpdateMaskForRaid();
}

void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 arg)
{
    WorldPacket data(SMSG_TRANSFER_ABORTED, 4 + 2);
    data << uint32(mapid);
    data << uint8(arg);
    data.WriteBits(reason, 5);
    data.FlushBits();

    GetSession()->SendPacket(&data);
}

void Player::SendRaidInstanceMessage(uint32 p_MapID, Difficulty p_Difficulty, uint32 p_Time)
{
    // Type of warning, based on the time remaining until reset
    uint32 l_Type;
    if (p_Time > 3600)
        l_Type = RAID_INSTANCE_WELCOME;
    else if (p_Time > 900 && p_Time <= 3600)
        l_Type = RAID_INSTANCE_WARNING_HOURS;
    else if (p_Time > 300 && p_Time <= 900)
        l_Type = RAID_INSTANCE_WARNING_MIN;
    else
        l_Type = RAID_INSTANCE_WARNING_MIN_SOON;

    WorldPacket l_Data(SMSG_RAID_INSTANCE_MESSAGE, 1 + 4 * 3 + 1);
    l_Data << uint8(l_Type);
    l_Data << uint32(p_MapID);
    l_Data << uint32(p_Difficulty);
    l_Data << int32(p_Time);

    l_Data.WriteBit(0);                                   // is locked
    l_Data.WriteBit(0);                                   // is extended, ignored if prev field is 0
    l_Data.FlushBits();
    GetSession()->SendPacket(&l_Data);
}

void Player::SendInstanceGroupSizeChanged(uint32 p_Size)
{
    WorldPacket l_Data(Opcodes::SMSG_INSTANCE_GROUP_SIZE_CHANGED, 4);
    l_Data << uint32(p_Size);
    GetSession()->SendPacket(&l_Data);
}

void Player::ApplyEquipCooldown(Item* p_Item)
{
    if (p_Item->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FLAG_NO_EQUIP_COOLDOWN))
        return;

    for (uint8 l_I = 0; l_I < MAX_ITEM_PROTO_SPELLS; ++l_I)
    {
        _Spell const& l_SpellData = p_Item->GetTemplate()->Spells[l_I];

        // no spell
        if (!l_SpellData.SpellId)
            continue;

        // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
        if (l_SpellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE)
            continue;

        //! Don't replace longer cooldowns by equi cooldown if we have any.
        SpellCooldowns::iterator l_It = m_spellCooldowns.find(l_SpellData.SpellId);

        if (l_It != m_spellCooldowns.end() && l_It->second.itemid == p_Item->GetEntry() && l_It->second.end > uint64((time(NULL) + 30) * IN_MILLISECONDS))
            continue;

        AddSpellCooldown(l_SpellData.SpellId, p_Item->GetEntry(), 30 * IN_MILLISECONDS);

        WorldPacket l_Data(SMSG_ITEM_COOLDOWN, 12);
        l_Data.appendPackGUID(p_Item->GetGUID());
        l_Data << uint32(l_SpellData.SpellId);
        GetSession()->SendPacket(&l_Data);
    }
}

void Player::resetSpells(bool myClassOnly)
{
    // not need after this call
    if (HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
        RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS, true);

    // make full copy of map (spells removed and marked as deleted at another spell remove
    // and we can't use original map for safe iterative with visit each spell at loop end
    PlayerSpellMap smap = GetSpellMap();

    uint32 family;

    if (myClassOnly)
    {
        ChrClassesEntry const* clsEntry = sChrClassesStore.LookupEntry(getClass());
        if (!clsEntry)
            return;
        family = clsEntry->SpellClassSet;

        for (PlayerSpellMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter)
        {
            SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(iter->first);
            if (!spellInfo)
                continue;

            // skip server-side/triggered spells
            if (spellInfo->SpellLevel == 0)
                continue;

            // skip wrong class/race skills
            if (!IsSpellFitByClassAndRace(spellInfo->Id))
                continue;

            // skip other spell families
            if (spellInfo->SpellFamilyName != family)
                continue;

            // skip broken spells
            if (!SpellMgr::IsSpellValid(spellInfo, this, false))
                continue;
        }
    }
    else
        for (PlayerSpellMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter)
            removeSpell(iter->first, false, false);           // only iter->first can be accessed, object by iter->second can be deleted already

    learnDefaultSpells();
    learnQuestRewardedSpells();
}

void Player::learnDefaultSpells()
{
    // learn default race/class spells
    PlayerInfo const* info = sObjectMgr->GetPlayerInfo(getRace(), getClass());
    for (PlayerCreateInfoSpells::const_iterator itr = info->customSpells.begin(); itr != info->customSpells.end(); ++itr)
    {
        uint32 tspell = *itr;
        sLog->outDebug(LOG_FILTER_PLAYER_LOADING, "PLAYER (Class: %u Race: %u): Adding initial spell, id = %u", uint32(getClass()), uint32(getRace()), tspell);
        if (!IsInWorld())                                    // will send in INITIAL_SPELLS in list anyway at map add
            addSpell(tspell, true, true, true, false);
        else                                                // but send in normal spell in game learn case
            learnSpell(tspell, true);
    }

    if (getRace() == RACE_PANDAREN_HORDE)
    {
        uint32 spellLangHorde[2] = {669, 108127};
        for (int i = 0; i < 2; i++)
        {
            if (!IsInWorld())                                    // will send in INITIAL_SPELLS in list anyway at map add
                addSpell(spellLangHorde[i], true, true, true, false);
            else                                                // but send in normal spell in game learn case
                learnSpell(spellLangHorde[i], true);
        }
    }

    if (getRace() == RACE_PANDAREN_ALLI)
    {
        uint32 spellLangAlliance[2] = {668,108127};
        for (int i = 0; i < 2; i++)
        {
            if (!IsInWorld())                                    // will send in INITIAL_SPELLS in list anyway at map add
                addSpell(spellLangAlliance[i], true, true, true, false);
            else                                                // but send in normal spell in game learn case
                learnSpell(spellLangAlliance[i], true);
        }
    }
}

void Player::learnQuestRewardedSpells(Quest const* quest)
{
    int32 spell_id = quest->GetRewSpellCast();
    uint32 src_spell_id = quest->GetSrcSpell();

    // skip quests without rewarded spell
    if (!spell_id)
        return;

    // if RewSpellCast = -1 we remove aura do to SrcSpell from player.
    if (spell_id == -1 && src_spell_id)
    {
        RemoveAurasDueToSpell(src_spell_id);
        return;
    }

    SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id);
    if (!spellInfo)
        return;

    // check learned spells state
    bool found = false;
    for (uint8 i = 0; i < spellInfo->EffectCount; ++i)
    {
        if (spellInfo->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->Effects[i].TriggerSpell))
        {
            found = true;
            break;
        }
    }

    // skip quests with not teaching spell or already known spell
    if (!found)
        return;

    uint32 learned_0 = spellInfo->Effects[0].TriggerSpell;
    if (!HasSpell(learned_0))
    {
        SpellInfo const* learnedInfo = sSpellMgr->GetSpellInfo(learned_0);
        if (!learnedInfo)
            return;

        // profession specialization can be re-learned from npc
        if (learnedInfo->Effects[0].Effect == SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effects[1].Effect == 0 && !learnedInfo->SpellLevel)
            return;
    }

    CastSpell(this, spell_id, true);
}

void Player::learnQuestRewardedSpells()
{
    // learn spells received from quest completing
    for (RewardedQuestSet::const_iterator itr = m_RewardedQuests.begin(); itr != m_RewardedQuests.end(); ++itr)
    {
        Quest const* quest = sObjectMgr->GetQuestTemplate(*itr);
        if (!quest)
            continue;

        learnQuestRewardedSpells(quest);
    }
}

void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value)
{
    uint32 raceMask  = getRaceMask();
    uint32 classMask = getClassMask();
    for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
    {
        SkillLineAbilityEntry const* pAbility = sSkillLineAbilityStore.LookupEntry(j);
        if (!pAbility || pAbility->skillId != skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
            continue;
        // Check race if set
        if (pAbility->racemask && !(pAbility->racemask & raceMask))
            continue;
        // Check class if set
        if (pAbility->classmask && !(pAbility->classmask & classMask))
            continue;

        if (sSpellMgr->GetSpellInfo(pAbility->spellId))
        {
            // need unlearn spell
            if (skill_value < pAbility->req_skill_value)
                removeSpell(pAbility->spellId);
            // need learn
            else if (!IsInWorld())
                addSpell(pAbility->spellId, true, true, true, false);
            else
                learnSpell(pAbility->spellId, true);
        }
    }
}

void Player::SendAurasForTarget(Unit* p_Target)
{
    if (!p_Target || p_Target->GetVisibleAuras()->empty())                  // speedup things
        return;

    /// Blizz sends certain movement packets sometimes even before CreateObject
    if (p_Target->HasAuraType(SPELL_AURA_FEATHER_FALL))
        p_Target->SetFeatherFall(true, true);

    if (p_Target->HasAuraType(SPELL_AURA_WATER_WALK))
        p_Target->SetWaterWalking(true, true);

    if (p_Target->HasAuraType(SPELL_AURA_HOVER))
        p_Target->SetHover(true, true);

    Unit::VisibleAuraMap const* l_VisibleAuras = p_Target->GetVisibleAuras();

    uint32 l_AuraCount = 0;
    for (Unit::VisibleAuraMap::const_iterator itr = l_VisibleAuras->begin(); itr != l_VisibleAuras->end(); ++itr)
    {
        AuraApplication * l_AuraApplication = itr->second;

        if (!l_AuraApplication || !l_AuraApplication->GetBase())
            continue;

        ++l_AuraCount;
    }

    WorldPacket l_Data(SMSG_AURA_UPDATE, 2 * 1024);
    l_Data.WriteBit(true);                          ///< Update All
    l_Data.FlushBits();
    l_Data.appendPackGUID(p_Target->GetGUID());     ///< Unit GUID
    l_Data << uint32(l_AuraCount);                  ///< Auras count

    if (l_AuraCount)
    {
        for (Unit::VisibleAuraMap::const_iterator l_It = l_VisibleAuras->begin(); l_It != l_VisibleAuras->end(); ++l_It)
        {
            AuraApplication * l_AuraApplication = l_It->second;

            if (!l_AuraApplication || !l_AuraApplication->GetBase())
                continue;

            l_AuraApplication->BuildUpdatePacket(l_Data, false);
        }
    }

    GetSession()->SendPacket(&l_Data);
}

void Player::SetDailyQuestStatus(uint32 quest_id)
{
    if (Quest const* qQuest = sObjectMgr->GetQuestTemplate(quest_id))
    {
        if (!qQuest->IsDFQuest())
        {
            m_dailyQuestStorage.insert(quest_id);
            m_lastDailyQuestTime = time(NULL);              // last daily quest time
            m_DailyQuestChanged = true;

            if (m_dailyQuestStorage.size() - 1 < DynamicFields::Count)
                SetDynamicValue(PLAYER_DYNAMIC_FIELD_DAILY_QUESTS_COMPLETED, m_dailyQuestStorage.size() - 1, quest_id);
        }
        else
        {
            m_DFQuests.insert(quest_id);
            m_lastDailyQuestTime = time(NULL);
            m_DailyQuestChanged = true;
        }
    }
}

void Player::SetWeeklyQuestStatus(uint32 quest_id)
{
    m_weeklyquests.insert(quest_id);
    m_WeeklyQuestChanged = true;
}

void Player::SetSeasonalQuestStatus(uint32 quest_id)
{
    Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id);
    if (!quest)
        return;

    m_seasonalquests[sGameEventMgr->GetEventIdForQuest(quest)].insert(quest_id);
    m_SeasonalQuestChanged = true;
}

void Player::SetMonthlyQuestStatus(uint32 quest_id)
{
    m_monthlyquests.insert(quest_id);
    m_MonthlyQuestChanged = true;
}

void Player::ResetDailyQuestStatus()
{
    m_dailyQuestStorage.clear();

    std::vector<uint32> l_Dailies = GetDynamicValues(PLAYER_DYNAMIC_FIELD_DAILY_QUESTS_COMPLETED);
    if (!l_Dailies.empty())
    {
        std::vector<uint32> l_QuestBits;
        for (uint32 questId : l_Dailies)
        {
            if (uint32 questBit = GetQuestUniqueBitFlag(questId))
                l_QuestBits.push_back(questBit);
        }

        if (!l_QuestBits.empty())
            ClearQuestBits(l_QuestBits);
    }

    ClearDynamicValue(PLAYER_DYNAMIC_FIELD_DAILY_QUESTS_COMPLETED);
    m_DFQuests.clear(); // Dungeon Finder Quests.

    // DB data deleted in caller
    m_DailyQuestChanged = false;
    m_lastDailyQuestTime = 0;

    WorldPacket data(SMSG_DAILY_QUESTS_RESET);
    data << uint32(l_Dailies.size());
    GetSession()->SendPacket(&data);
}

void Player::ResetGarrisonDatas()
{
    using namespace MS::Garrison;
    if (Manager* l_Garrison = GetGarrison())
    {
        if (l_Garrison->HasActiveBuilding(Buildings::LunarfallInn_FrostwallTavern_Level1) && l_Garrison->GetPlot(m_positionX, m_positionY, m_positionZ).PlotInstanceID != 0)
        {
            std::vector<uint64> l_CreatureGuids = l_Garrison->GetBuildingCreaturesByBuildingType(BuildingType::Inn);

            for (std::vector<uint64>::iterator l_Itr = l_CreatureGuids.begin(); l_Itr != l_CreatureGuids.end(); ++l_Itr)
            {
                if (Creature* l_Creature = sObjectAccessor->GetCreature(*this, *l_Itr))
                {
                    if (l_Creature->AI())
                        l_Creature->AI()->SetData(CreatureAIDataIDs::DailyReset, 0);
                }
            }
        }

        if (l_Garrison->HasActiveBuilding(Buildings::Stables_Stables_Level1) && l_Garrison->GetPlot(m_positionX, m_positionY, m_positionZ).PlotInstanceID != 0)
        {
            if (uint64 l_Value = GetCharacterWorldStateValue(CharacterWorldStates::CharWorldStateGarrisonStablesFirstQuest))
                SetCharacterWorldState(CharacterWorldStates::CharWorldStateGarrisonStablesFirstQuest, l_Value &= ~StablesData::g_PendingQuestFlag);

            if (uint64 l_Value = GetCharacterWorldStateValue(CharacterWorldStates::CharWorldStateGarrisonStablesSecondQuest))
                SetCharacterWorldState(CharacterWorldStates::CharWorldStateGarrisonStablesSecondQuest, l_Value &= ~StablesData::g_PendingQuestFlag);
        }

        if (l_Garrison->HasActiveBuilding(Buildings::GnomishGearworks_GoblinWorkshop_Level1) && l_Garrison->GetPlot(m_positionX, m_positionY, m_positionZ).PlotInstanceID != 0)
        {
            std::vector<uint64> l_CreatureGuids = l_Garrison->GetBuildingCreaturesByBuildingType(BuildingType::Workshop);

            for (std::vector<uint64>::iterator l_Itr = l_CreatureGuids.begin(); l_Itr != l_CreatureGuids.end(); ++l_Itr)
            {
                if (Creature* l_Creature = sObjectAccessor->GetCreature(*this, *l_Itr))
                {
                    if (l_Creature->AI())
                        l_Creature->AI()->SetData(CreatureAIDataIDs::DailyReset, 0);
                }
            }
        }

        if (l_Garrison->HasBuildingType(BuildingType::Type::TradingPost) && l_Garrison->GetPlot(m_positionX, m_positionY, m_positionZ).PlotInstanceID != 0)
        {
            std::vector<uint64> l_CreatureGuids = l_Garrison->GetBuildingCreaturesByBuildingType(BuildingType::Type::TradingPost);
            std::vector<uint32> l_TradingPostShipments = { 138, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 196 };

            SetCharacterWorldState(CharacterWorldStates::CharWorldStateGarrisonTradingPostDailyRandomShipment, l_TradingPostShipments[urand(0, l_TradingPostShipments.size() - 1)]);

            for (std::vector<uint64>::iterator l_Itr = l_CreatureGuids.begin(); l_Itr != l_CreatureGuids.end(); ++l_Itr)
            {
                if (Creature* l_Creature = sObjectAccessor->GetCreature(*this, *l_Itr))
                {
                    if (l_Creature->AI())
                        l_Creature->AI()->SetData(CreatureAIDataIDs::DailyReset, 0);
                }
            }
        }
    }
}

void Player::ResetWeeklyQuestStatus()
{
    if (m_weeklyquests.empty())
        return;

    std::vector<uint32> l_QuestBits;
    for (uint32 questId : m_weeklyquests)
    {
        if (uint32 questBit = GetQuestUniqueBitFlag(questId))
            l_QuestBits.push_back(questBit);
    }

    if (!l_QuestBits.empty())
        ClearQuestBits(l_QuestBits);

    m_weeklyquests.clear();
    // DB data deleted in caller
    m_WeeklyQuestChanged = false;
}

void Player::ResetSeasonalQuestStatus(uint16 event_id)
{
    auto eventItr = m_seasonalquests.find(event_id);
    if (eventItr == m_seasonalquests.end())
        return;

    if (eventItr->second.empty())
        return;

    std::vector<uint32> l_QuestBits;
    for (uint32 questId : eventItr->second)
    {
        if (uint32 questBit = GetQuestUniqueBitFlag(questId))
            l_QuestBits.push_back(questBit);
    }

    if (!l_QuestBits.empty())
        ClearQuestBits(l_QuestBits);

    m_seasonalquests.erase(eventItr);
    // DB data deleted in caller
    m_SeasonalQuestChanged = false;
}

void Player::ResetMonthlyQuestStatus()
{
    if (m_monthlyquests.empty())
        return;

    std::vector<uint32> l_QuestBits;
    for (uint32 questId : m_monthlyquests)
    {
        if (uint32 questBit = GetQuestUniqueBitFlag(questId))
            l_QuestBits.push_back(questBit);
    }

    if (!l_QuestBits.empty())
        ClearQuestBits(l_QuestBits);

    m_monthlyquests.clear();
    // DB data deleted in caller
    m_MonthlyQuestChanged = false;
}

Battleground* Player::GetBattleground() const
{
    if (GetBattlegroundId() == 0)
        return NULL;

    return sBattlegroundMgr->GetBattleground(GetBattlegroundId(), MS::Battlegrounds::GetSchedulerType(m_bgData.bgTypeID));
}

bool Player::InArena() const
{
    Battleground* bg = GetBattleground();
    if (!bg || !bg->isArena())
        return false;

    return true;
}

bool Player::InRatedBattleGround() const
{
    Battleground* bg = GetBattleground();
    if (!bg || !bg->IsRatedBG())
        return false;

    return true;
}

bool Player::GetBGAccessByLevel(BattlegroundTypeId bgTypeId) const
{
    // get a template bg instead of running one
    Battleground* bg = sBattlegroundMgr->GetBattlegroundTemplate(MS::Battlegrounds::GetSchedulerType(bgTypeId));
    if (!bg)
        return false;

    // limit check leel to dbc compatible level range
    uint32 level = getLevel();
    if (level > DEFAULT_MAX_LEVEL)
        level = DEFAULT_MAX_LEVEL;

    if (level < bg->GetMinLevel() || level > bg->GetMaxLevel())
        return false;

    return true;
}

float Player::GetReputationPriceDiscount(Creature const* creature) const
{
    FactionTemplateEntry const* vendor_faction = creature->getFactionTemplateEntry();
    if (!vendor_faction || !vendor_faction->Faction)
        return 1.0f;

    ReputationRank rank = GetReputationRank(vendor_faction->Faction);
    if (rank <= REP_NEUTRAL)
        return 1.0f;

    return 1.0f - 0.05f* (rank - REP_NEUTRAL);
}

bool Player::IsSpellFitByClassAndRace(uint32 p_SpellId) const
{
    uint32 l_RaceMask  = getRaceMask();
    uint32 l_ClassMask = getClassMask();
    auto l_Spellinfo   = sSpellMgr->GetSpellInfo(p_SpellId);

    if (l_Spellinfo == nullptr)
        return false;

    SkillLineAbilityMapBounds l_Bounds = sSpellMgr->GetSkillLineAbilityMapBounds(p_SpellId);
    if (l_Bounds.first == l_Bounds.second)
        return true;

    for (SkillLineAbilityMap::const_iterator l_SpellIdx = l_Bounds.first; l_SpellIdx != l_Bounds.second; ++l_SpellIdx)
    {
        // Hackfix, Gift of the Naaru for Monks (121093) doesn't have a racemask for only Draenei
        if (p_SpellId == 121093 && l_RaceMask != 1024)
            continue;

        /// Skip horde or alliance only spells
        if ((l_Spellinfo->AttributesEx7 & SPELL_ATTR7_HORDE_ONLY && (l_RaceMask & RACEMASK_HORDE) == 0)
            || (l_Spellinfo->AttributesEx7 & SPELL_ATTR7_ALLIANCE_ONLY && (l_RaceMask & RACEMASK_ALLIANCE) == 0))
            continue;

        // skip wrong race skills
        if (l_SpellIdx->second->racemask && (l_SpellIdx->second->racemask & l_RaceMask) == 0)
            continue;

        // skip wrong class skills
        if (l_SpellIdx->second->classmask && (l_SpellIdx->second->classmask & l_ClassMask) == 0)
            continue;

        return true;
    }

    return false;
}

bool Player::HasQuestForGO(uint32 GOId) const
{
    for (uint8 i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
    {
        uint32 questid = GetQuestSlotQuestId(i);
        if (questid == 0)
            continue;

        QuestStatusMap::const_iterator qs_itr = m_QuestStatus.find(questid);
        if (qs_itr == m_QuestStatus.end())
            continue;

        QuestStatusData const& qs = qs_itr->second;

        if (qs.Status == QUEST_STATUS_INCOMPLETE)
        {
            Quest const* qinfo = sObjectMgr->GetQuestTemplate(questid);
            if (!qinfo)
                continue;

            if (GetGroup() && GetGroup()->isRaidGroup() && !qinfo->IsAllowedInRaid())
                continue;

            for (QuestObjective l_Objective : qinfo->QuestObjectives)
            {
                if (l_Objective.Type == QUEST_OBJECTIVE_TYPE_GO)
                {
                    if (GOId == (uint32)l_Objective.ObjectID && GetQuestObjectiveCounter(l_Objective.ID) < uint32(l_Objective.Amount))
                        return true;
                }
            }
        }
    }
    return false;
}
uint32 Player::GetQuestObjectiveCounter(uint32 objectiveId) const
{
    QuestObjectiveStatusMap::const_iterator citr = m_questObjectiveStatus.find(objectiveId);
        if (citr != m_questObjectiveStatus.end())
            return citr->second;

    return 0;
}

void Player::UpdateForQuestWorldObjects()
{
    if (m_clientGUIDs.empty())
        return;

    UpdateData udata(GetMapId());
    WorldPacket packet;
    for (auto itr=m_clientGUIDs.begin(); itr != m_clientGUIDs.end(); ++itr)
    {
        if (IS_GAMEOBJECT_GUID(*itr))
        {
            if (GameObject* obj = HashMapHolder<GameObject>::Find(*itr))
                obj->BuildValuesUpdateBlockForPlayer(&udata, this);
        }
        else if (IS_CRE_OR_VEH_GUID(*itr))
        {
            Creature* obj = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr);
            if (!obj)
                continue;

            // check if this unit requires quest specific flags
            if (!obj->HasFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK))
                continue;

            SpellClickInfoMapBounds clickPair = sObjectMgr->GetSpellClickInfoMapBounds(obj->GetEntry());
            for (SpellClickInfoContainer::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
            {
                //! This code doesn't look right, but it was logically converted to condition system to do the exact
                //! same thing it did before. It definitely needs to be overlooked for intended functionality.
                if (ConditionContainer const* conds = sConditionMgr->GetConditionsForSpellClickEvent(obj->GetEntry(), _itr->second.spellId))
                {
                    bool buildUpdateBlock = false;
                    for (ConditionContainer::const_iterator jtr = conds->begin(); jtr != conds->end() && !buildUpdateBlock; ++jtr)
                        if ((*jtr)->ConditionType == CONDITION_QUESTREWARDED || (*jtr)->ConditionType == CONDITION_QUESTTAKEN)
                            buildUpdateBlock = true;

                    if (buildUpdateBlock)
                    {
                        obj->BuildValuesUpdateBlockForPlayer(&udata, this);
                        break;
                    }
                }
            }
        }
    }

    if (udata.BuildPacket(&packet))
        GetSession()->SendPacket(&packet);
}

void Player::SummonIfPossible(bool agree)
{
    if (!agree)
    {
        m_summon_expire = 0;
        return;
    }

    // expire and auto declined
    if (m_summon_expire < time(NULL))
        return;

    // stop taxi flight at summon
    if (isInFlight())
    {
        GetMotionMaster()->MovementExpired();
        CleanupAfterTaxiFlight();
    }

    // drop flag at summon
    // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
    if (Battleground* bg = GetBattleground())
        bg->EventPlayerDroppedFlag(this);

    m_summon_expire = 0;

    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);

    TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z, GetOrientation());
}

void Player::RemoveItemDurations(Item* item)
{
    for (ItemDurationList::iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
    {
        if (*itr == item)
        {
            m_itemDuration.erase(itr);
            break;
        }
    }
}

void Player::AddItemDurations(Item* item)
{
    if (item->GetUInt32Value(ITEM_FIELD_EXPIRATION))
    {
        m_itemDuration.push_back(item);
        item->SendTimeUpdate(this);
    }
}

void Player::AutoUnequipOffhandIfNeed(bool force /*= false*/)
{
    Item* offItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
    if (!offItem)
        return;

     // unequip offhand weapon if player doesn't have dual wield anymore
     if (!CanDualWield() && (offItem->GetTemplate()->InventoryType == INVTYPE_WEAPONOFFHAND || offItem->GetTemplate()->InventoryType == INVTYPE_WEAPON))
          force = true;

    // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
    if (!force && (CanTitanGrip() || (offItem->GetTemplate()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed())))
        return;

    ItemPosCountVec off_dest;
    uint8 off_msg = CanStoreItem(NULL_BAG, NULL_SLOT, off_dest, offItem, false);
    if (off_msg == EQUIP_ERR_OK)
    {
        RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
        StoreItem(off_dest, offItem, true);
    }
    else
    {
        MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
        SQLTransaction trans = CharacterDatabase.BeginTransaction();
        offItem->DeleteFromInventoryDB(trans);                   // deletes item from character's inventory
        offItem->SaveToDB(trans);                                // recursive and not have transaction guard into self, item not in inventory and can be save standalone

        std::string subject = GetSession()->GetTrinityString(LANG_NOT_EQUIPPED_ITEM);
        MailDraft(subject, "There were problems with equipping one or several items").AddItem(offItem).SendMailTo(trans, this, MailSender(this, MAIL_STATIONERY_GM), MAIL_CHECK_MASK_COPIED);

        CharacterDatabase.CommitTransaction(trans);
    }
}

OutdoorPvP* Player::GetOutdoorPvP() const
{
    return sOutdoorPvPMgr->GetOutdoorPvPToZoneId(GetZoneId());
}

bool Player::HasItemFitToSpellRequirements(SpellInfo const* spellInfo, Item const* ignoreItem) const
{
    if (spellInfo->EquippedItemClass < 0)
        return true;

    // scan other equipped items for same requirements (mostly 2 daggers/etc)
    // for optimize check 2 used cases only
    switch (spellInfo->EquippedItemClass)
    {
        case ITEM_CLASS_WEAPON:
        {
            for (uint8 i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
                if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i))
                    if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
                        return true;
            break;
        }
        case ITEM_CLASS_ARMOR:
        {
            // tabard not have dependent spells
            for (uint8 i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
                if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, i))
                    if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
                        return true;

            // shields can be equipped to offhand slot
            if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
                if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
                    return true;

            // ranged slot can have some armor subclasses
            if (Item* item = GetUseableItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
                if (item != ignoreItem && item->IsFitToSpellRequirements(spellInfo))
                    return true;

            break;
        }
        default:
            sLog->outError(LOG_FILTER_PLAYER, "HasItemFitToSpellRequirements: Not handled spell requirement for item class %u", spellInfo->EquippedItemClass);
            break;
    }

    return false;
}

bool Player::CanNoReagentCast(SpellInfo const* spellInfo) const
{
    // don't take reagents for spells with SPELL_ATTR5_NO_REAGENT_WHILE_PREP
    if (spellInfo->AttributesEx5 & SPELL_ATTR5_NO_REAGENT_WHILE_PREP &&
        HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
        return true;

    // Check no reagent use mask
    flag128 noReagentMask;
    noReagentMask[0] = GetUInt32Value(PLAYER_FIELD_NO_REAGENT_COST_MASK);
    noReagentMask[1] = GetUInt32Value(PLAYER_FIELD_NO_REAGENT_COST_MASK+1);
    noReagentMask[2] = GetUInt32Value(PLAYER_FIELD_NO_REAGENT_COST_MASK+2);
    noReagentMask[3] = GetUInt32Value(PLAYER_FIELD_NO_REAGENT_COST_MASK+3);
    if (spellInfo->SpellFamilyFlags & noReagentMask)
        return true;

    return false;
}

void Player::RemoveItemDependentAurasAndCasts(Item* pItem)
{
    for (AuraMap::iterator itr = m_ownedAuras.begin(); itr != m_ownedAuras.end();)
    {
        Aura* aura = itr->second;

        // skip passive (passive item dependent spells work in another way) and not self applied auras
        SpellInfo const* spellInfo = aura->GetSpellInfo();
        if (aura->IsPassive() ||  aura->GetCasterGUID() != GetGUID())
        {
            ++itr;
            continue;
        }

        // skip if not item dependent or have alternative item
        if (HasItemFitToSpellRequirements(spellInfo, pItem))
        {
            ++itr;
            continue;
        }

        // no alt item, remove aura, restart check
        RemoveOwnedAura(itr);
    }

    // currently casted spells can be dependent from item
    for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
        if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
            if (spell->getState() != SPELL_STATE_DELAYED && !HasItemFitToSpellRequirements(spell->m_spellInfo, pItem))
                InterruptSpell(CurrentSpellTypes(i));
}

uint32 Player::GetResurrectionSpellId()
{
    // search priceless resurrection possibilities
    uint32 l_Priority = 0;
    uint32 l_ResurrectSpellID = 0;

    AuraEffectList const& l_DummyAuras = GetAuraEffectsByType(SPELL_AURA_DUMMY);
    for (AuraEffectList::const_iterator l_AuraItr = l_DummyAuras.begin(); l_AuraItr != l_DummyAuras.end(); ++l_AuraItr)
    {
        // Soulstone Resurrection                           // prio: 3 (max, non death persistent)
        if (l_Priority < 2 && (*l_AuraItr)->GetId() == 20707)
        {
            l_Priority = 3;
            l_ResurrectSpellID = 3026;
        }
        // Twisting Nether                                  // prio: 2 (max)
        else if ((*l_AuraItr)->GetId() == 23701 && roll_chance_i(10))
        {
            l_Priority = 2;
            l_ResurrectSpellID = 23700;
        }
    }

    // Reincarnation (passive spell)  // prio: 1
    if (l_Priority < 1 && HasSpell(20608) && !HasSpellCooldown(21169))
        l_ResurrectSpellID = 21169;

    return l_ResurrectSpellID;
}

// Used in triggers for check "Only to targets that grant experience or honor" req
bool Player::isHonorOrXPTarget(Unit* victim)
{
    uint8 v_level = victim->getLevel();
    uint8 k_grey  = JadeCore::XP::GetGrayLevel(getLevel());

    // Victim level less gray level
    if (v_level <= k_grey)
        return false;

    if (victim->GetTypeId() == TYPEID_UNIT)
    {
        if (victim->ToCreature()->isTotem() ||
            victim->ToCreature()->isPet() ||
            victim->ToCreature()->GetCreatureTemplate()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
                return false;
    }
    return true;
}

bool Player::GetsRecruitAFriendBonus(bool forXP)
{
    bool recruitAFriend = false;
    if (getLevel() <= sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL) || !forXP)
    {
        if (Group* group = this->GetGroup())
        {
            for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
            {
                Player* player = itr->getSource();
                if (!player)
                    continue;

                if (!player->IsAtRecruitAFriendDistance(this))
                    continue;                               // member (alive or dead) or his corpse at req. distance

                if (forXP)
                {
                    // level must be allowed to get RaF bonus
                    if (player->getLevel() > sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL))
                        continue;

                    // level difference must be small enough to get RaF bonus, UNLESS we are lower level
                    if (player->getLevel() < getLevel())
                        if (uint8(getLevel() - player->getLevel()) > sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL_DIFFERENCE))
                            continue;
                }

                bool ARecruitedB = (player->GetSession()->GetRecruiterId() == GetSession()->GetAccountId());
                bool BRecruitedA = (GetSession()->GetRecruiterId() == player->GetSession()->GetAccountId());
                if (ARecruitedB || BRecruitedA)
                {
                    recruitAFriend = true;
                    break;
                }
            }
        }
    }
    return recruitAFriend;
}

void Player::RewardPersonnalCurrencies(Unit* p_Victim)
{
    if (!p_Victim || p_Victim->IsPlayer())
        return;

    if (!p_Victim->ToCreature())
        return;

    if (!p_Victim->ToCreature()->GetEntry())
        return;

    if (uint32 l_TrackingQuestId = Vignette::GetTrackingQuestIdFromWorldObject(p_Victim))
    {
        uint32 l_QuestBit = GetQuestUniqueBitFlag(l_TrackingQuestId);
        if (IsQuestBitFlaged(l_QuestBit))
            return;
    }

    CurrencyOnKillEntry const* l_Curr = sObjectMgr->GetPersonnalCurrencyOnKillEntry(p_Victim->ToCreature()->GetEntry());
    if (!l_Curr)
        return;

    bool l_Result = true;
    if (p_Victim->ToCreature()->AI())
        p_Victim->ToCreature()->AI()->CurrenciesRewarder(l_Result);

    if (!l_Result)
        return;

    for (CurrencyOnKillEntry::const_iterator l_Iter = l_Curr->begin(); l_Iter != l_Curr->end(); ++l_Iter)
    {
        int32 l_Pct = 100;
        Unit::AuraEffectList const& l_Auras = GetAuraEffectsByType(SPELL_AURA_MOD_CURRENCY_GAIN_PCT);
        for (Unit::AuraEffectList::const_iterator l_I = l_Auras.begin(); l_I != l_Auras.end(); ++l_I)
        {
            if (l_Iter->first == (*l_I)->GetMiscValue()) ///< Comparison of integers of different signs: 'const unsigned int' and 'int32' (aka 'int')
                l_Pct += (*l_I)->GetAmount();
        }

        ModifyCurrency(l_Iter->first, CalculatePct(l_Iter->second, l_Pct));
    }
}

void Player::RewardPlayerAndGroupAtKill(Unit* victim, bool isBattleGround)
{
    if (Group *pGroup = GetGroup())
    {
        for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
        {
            Player* pGroupGuy = itr->getSource();
            if (IsInMap(pGroupGuy))
                pGroupGuy->RewardCurrencyAtKill(victim);
        }
    }
    else
        RewardCurrencyAtKill(victim);

    KillRewarder(this, victim, isBattleGround).Reward();
}

void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
{
    if (!pRewardSource)
        return;
    uint64 creature_guid = (pRewardSource->GetTypeId() == TYPEID_UNIT) ? pRewardSource->GetGUID() : uint64(0);

    // prepare data for near group iteration
    if (Group* group = GetGroup())
    {
        for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
        {
            Player* player = itr->getSource();
            if (!player)
                continue;

            if (!player->IsAtGroupRewardDistance(pRewardSource))
                continue;                               // member (alive or dead) or his corpse at req. distance

            // quest objectives updated only for alive group member or dead but with not released body
            if (player->isAlive()|| !player->GetCorpse())
                player->KilledMonsterCredit(creature_id, creature_guid);
        }
    }
    else                                                    // if (!group)
        KilledMonsterCredit(creature_id, creature_guid);
}

bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
{
    if (!pRewardSource)
        return false;
    const WorldObject* player = GetCorpse();
    if (!player || isAlive())
        player = this;

    if (player->GetMapId() != pRewardSource->GetMapId() || player->GetInstanceId() != pRewardSource->GetInstanceId())
        return false;

    return pRewardSource->GetDistance(player) <= sWorld->getFloatConfig(CONFIG_GROUP_XP_DISTANCE);
}

bool Player::IsAtRecruitAFriendDistance(WorldObject const* pOther) const
{
    if (!pOther)
        return false;
    const WorldObject* player = GetCorpse();
    if (!player || isAlive())
        player = this;

    if (player->GetMapId() != pOther->GetMapId() || player->GetInstanceId() != pOther->GetInstanceId())
        return false;

    return pOther->GetDistance(player) <= sWorld->getFloatConfig(CONFIG_MAX_RECRUIT_A_FRIEND_DISTANCE);
}

void Player::ResurectUsingRequestData()
{
    if (_resurrectionData->ResSpell != nullptr && _resurrectionData->ResSpell->IsBattleResurrection())
    {
        if (InstanceScript* l_InstanceScript = GetInstanceScript())
        {
            if (l_InstanceScript->CanUseCombatResurrection())
                l_InstanceScript->ConsumeCombatResurrectionCharge();
            else
            {
                /// Resurrecting - 60s aura preventing client from new res spells
                RemoveAura(160029);
                ClearResurrectRequestData();
                SendGameError(GameError::ERR_SPELL_FAILED_S, 236);
                SendForcedDeathUpdate();
                return;
            }
        }
    }

    /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
    float x, y, z, o;
    _resurrectionData->Location.GetPosition(x, y, z, o);
    TeleportTo(_resurrectionData->Location.GetMapId(), x, y, z, o);

    if (IsBeingTeleported())
    {
        ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
        return;
    }

    ResurrectPlayer(0.0f, false);

    if (GetMaxHealth() > _resurrectionData->Health)
        SetHealth(_resurrectionData->Health);
    else
        SetFullHealth();

    if (uint32(GetMaxPower(POWER_MANA)) > _resurrectionData->Mana)
        SetPower(POWER_MANA, _resurrectionData->Mana);
    else
        SetPower(POWER_MANA, GetMaxPower(POWER_MANA));

    SetPower(POWER_RAGE, 0);
    SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
    SetPower(POWER_FOCUS, GetMaxPower(POWER_FOCUS));
    SetPower(POWER_ECLIPSE, 0);
    SetPower(POWER_BURNING_EMBERS, 10);
    SetPower(POWER_SOUL_SHARDS, 100);
    SetPower(POWER_DEMONIC_FURY, 200);
    SetPower(POWER_SHADOW_ORB, 0);
    SetPower(POWER_CHI, 0);

    if (uint32 aura = _resurrectionData->Aura)
        CastSpell(this, aura, true, NULL, nullptr, _resurrectionData->GUID);

    SpawnCorpseBones();

    /// Resurrecting - 60s aura preventing client from new res spells
    RemoveAura(160029);
}

void Player::SendForcedDeathUpdate()
{
    WorldPacket l_Data(Opcodes::SMSG_FORCED_DEATH_UPDATE, 0);
    GetSession()->SendPacket(&l_Data);
}

void Player::SendGameError(GameError::Type p_Error, uint32 p_Data1 /*= 0xF0F0F0F0*/, uint32 p_Data2 /*= 0xF0F0F0F0*/)
{
    GetSession()->SendGameError(p_Error, p_Data1, p_Data2);
}

void Player::SetClientControl(Unit* p_Target, uint8 p_AllowMove)
{
    WorldPacket l_Data(SMSG_CLIENT_CONTROL_UPDATE);
    l_Data.appendPackGUID(p_Target->GetGUID());
    l_Data.WriteBit(p_AllowMove);
    GetSession()->SendPacket(&l_Data);

    if (p_Target == this && p_AllowMove)
        SetMover(this);
}

void Player::UpdateZoneDependentAuras(uint32 newZone)
{
    // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
    SpellAreaForAreaMapBounds saBounds = sSpellMgr->GetSpellAreaForAreaMapBounds(newZone);
    for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
        if (itr->second->autocast && itr->second->IsFitToRequirements(this, newZone, 0))
            if (!HasAura(itr->second->spellId))
                CastSpell(this, itr->second->spellId, true);
}

void Player::UpdateAreaDependentAuras(uint32 newArea)
{
    // remove auras from spells with area limitations
    for (AuraMap::iterator iter = m_ownedAuras.begin(); iter != m_ownedAuras.end();)
    {
        // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
        if (iter->second->GetSpellInfo()->CheckLocation(GetMapId(), m_zoneUpdateId, newArea, this) != SPELL_CAST_OK)
            RemoveOwnedAura(iter);
        else
            ++iter;
    }

    // some auras applied at subzone enter
    SpellAreaForAreaMapBounds saBounds = sSpellMgr->GetSpellAreaForAreaMapBounds(newArea);
    for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
        if (itr->second->autocast && itr->second->IsFitToRequirements(this, m_zoneUpdateId, newArea))
            if (!HasAura(itr->second->spellId))
                CastSpell(this, itr->second->spellId, true);

    if (newArea == 4273 && GetVehicle() && GetPositionX() > 400) // Ulduar
    {
        switch (GetVehicleBase()->GetEntry())
        {
            case 33062:
            case 33109:
            case 33060:
                GetVehicle()->Dismiss();
                break;
        }
    }
}

uint32 Player::GetCorpseReclaimDelay(bool pvp) const
{
    if (pvp)
    {
        if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP))
            return gCopseReclaimDelay[0];
    }
    else if (!sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE))
        return 0;

    time_t now = time(NULL);
    // 0..2 full period
    // should be ceil(x)-1 but not floor(x)
    uint64 count = (now < m_deathExpireTime - 1) ? (m_deathExpireTime - 1 - now)/DEATH_EXPIRE_STEP : 0;
    return gCopseReclaimDelay[count];
}

void Player::UpdateCorpseReclaimDelay()
{
    bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;

    if ((pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
        (!pvp && !sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE)))
        return;

    time_t now = time(NULL);
    if (now < m_deathExpireTime)
    {
        // full and partly periods 1..3
        uint64 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
        if (count < MAX_DEATH_COUNT)
            m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
        else
            m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
    }
    else
        m_deathExpireTime = now+DEATH_EXPIRE_STEP;
}

void Player::SendCorpseReclaimDelay(bool p_Load)
{
    Corpse * l_Corpse = GetCorpse();

    if (p_Load && !l_Corpse)
        return;

    bool l_IsPVP;

    if (l_Corpse)
        l_IsPVP = (l_Corpse->GetType() == CORPSE_RESURRECTABLE_PVP);
    else
        l_IsPVP = (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH);

    time_t l_Delay;

    if (p_Load)
    {
        if (l_Corpse->GetGhostTime() > m_deathExpireTime)
            return;

        uint64 l_Count;

        if ((l_IsPVP && sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
           (!l_IsPVP && sWorld->getBoolConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE)))
        {
            l_Count = (m_deathExpireTime-l_Corpse->GetGhostTime())/DEATH_EXPIRE_STEP;

            if (l_Count >= MAX_DEATH_COUNT)
                l_Count = MAX_DEATH_COUNT-1;
        }
        else
            l_Count=0;

        time_t l_ExpectedTime = l_Corpse->GetGhostTime() + gCopseReclaimDelay[l_Count];
        time_t l_Now          = time(NULL);

        if (l_Now >= l_ExpectedTime)
            return;

        l_Delay = l_ExpectedTime-l_Now;
    }
    else
        l_Delay = GetCorpseReclaimDelay(l_IsPVP);

    if (!l_Delay)
        return;

    /// Corpse reclaim delay 30 * 1000ms or longer at often deaths
    WorldPacket l_Data(SMSG_CORPSE_RECLAIM_DELAY, 4);
    l_Data << uint32(l_Delay * IN_MILLISECONDS);

    GetSession()->SendPacket(&l_Data);
}

Player* Player::GetNextRandomRaidMember(float radius)
{
    Group* group = GetGroup();
    if (!group)
        return NULL;

    std::vector<Player*> nearMembers;
    nearMembers.reserve(group->GetMembersCount());

    for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next())
    {
        Player* Target = itr->getSource();

        // IsHostileTo check duel and controlled by enemy
        if (Target && Target != this && IsWithinDistInMap(Target, radius) &&
            !Target->HasInvisibilityAura() && !IsHostileTo(Target))
            nearMembers.push_back(Target);
    }

    if (nearMembers.empty())
        return NULL;

    uint32 randTarget = urand(0, nearMembers.size()-1);
    return nearMembers[randTarget];
}

PartyResult Player::CanUninviteFromGroup() const
{
    Group const* grp = GetGroup();
    if (!grp)
        return ERR_NOT_IN_GROUP;

    if (grp->isLFGGroup())
    {
        uint64 gguid = grp->GetGUID();
        if (!sLFGMgr->GetKicksLeft(gguid))
            return ERR_PARTY_LFG_BOOT_LIMIT;

        LfgState state = sLFGMgr->GetState(gguid);
        if (state == LFG_STATE_BOOT)
            return ERR_PARTY_LFG_BOOT_IN_PROGRESS;

        if (grp->GetMembersCount() <= sLFGMgr->GetVotesNeeded(gguid))
            return ERR_PARTY_LFG_BOOT_TOO_FEW_PLAYERS;

        if (state == LFG_STATE_FINISHED_DUNGEON)
            return ERR_PARTY_LFG_BOOT_DUNGEON_COMPLETE;

        if (grp->isRollLootActive())
            return ERR_PARTY_LFG_BOOT_LOOT_ROLLS;

        // TODO: Should also be sent when anyone has recently left combat, with an aprox ~5 seconds timer.
        for (GroupReference const* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next())
            if (itr->getSource() && itr->getSource()->isInCombat())
                return ERR_PARTY_LFG_BOOT_IN_COMBAT;

        /* Missing support for these types
            return ERR_PARTY_LFG_BOOT_COOLDOWN_S;
            return ERR_PARTY_LFG_BOOT_NOT_ELIGIBLE_S;
        */
    }
    else
    {
        if (!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()) && !(grp->GetPartyFlags() & PARTY_FLAG_EVERYONE_IS_ASSISTANT))
            return ERR_NOT_LEADER;

        if (InBattleground())
            return ERR_LFG_PENDING;
    }

    return ERR_PARTY_RESULT_OK;
}

bool Player::isUsingLfg()
{
    uint64 guid = GetGUID();
    return sLFGMgr->GetState(guid) != LFG_STATE_NONE;
}

void Player::SetBattlegroundOrBattlefieldRaid(Group* group, int8 subgroup)
{
    //we must move references from m_group to m_originalGroup
    SetOriginalGroup(GetGroup(), GetSubGroup());

    m_group.unlink();
    m_group.link(group, this);
    m_group.setSubGroup((uint8)subgroup);
}

void Player::RemoveFromBattlegroundOrBattlefieldRaid()
{
    //remove existing reference
    m_group.unlink();
    if (Group* group = GetOriginalGroup())
    {
        m_group.link(group, this);
        m_group.setSubGroup(GetOriginalSubGroup());
    }
    SetOriginalGroup(NULL);
}

void Player::SetOriginalGroup(Group* group, int8 subgroup)
{
    if (group == NULL)
        m_originalGroup.unlink();
    else
    {
        // never use SetOriginalGroup without a subgroup unless you specify NULL for group
        ASSERT(subgroup >= 0);
        m_originalGroup.link(group, this);
        m_originalGroup.setSubGroup((uint8)subgroup);
    }
}

void Player::UpdateUnderwaterState(Map* m, float x, float y, float z)
{
    // temporary hack
    // player can't be on the ship and in the water at the same time
    // If this is not submarine
    if (GetTransport())
        return;

    LiquidData liquid_status;
    ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
    if (!res)
    {
        m_MirrorTimerFlags &= ~(UNDERWATER_INWATER | UNDERWATER_INLAVA | UNDERWATER_INSLIME | UNDERWARER_INDARKWATER);
        if (_lastLiquid && _lastLiquid->SpellId)
            RemoveAurasDueToSpell(_lastLiquid->SpellId);

        _lastLiquid = NULL;
        return;
    }

    if (uint32 liqEntry = liquid_status.entry)
    {
        LiquidTypeEntry const* liquid = sLiquidTypeStore.LookupEntry(liqEntry);
        if (_lastLiquid && _lastLiquid->SpellId && _lastLiquid->Id != liqEntry)
            RemoveAurasDueToSpell(_lastLiquid->SpellId);

        if (liquid && liquid->SpellId)
        {
            if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER))
            {
                if (!HasAura(liquid->SpellId))
                    CastSpell(this, liquid->SpellId, true);
            }
            else
                RemoveAurasDueToSpell(liquid->SpellId);
        }

        _lastLiquid = liquid;
    }
    else if (_lastLiquid && _lastLiquid->SpellId)
    {
        RemoveAurasDueToSpell(_lastLiquid->SpellId);
        _lastLiquid = NULL;
    }


    // All liquids type - check under water position
    if (liquid_status.type_flags & (MAP_LIQUID_TYPE_WATER | MAP_LIQUID_TYPE_OCEAN | MAP_LIQUID_TYPE_MAGMA | MAP_LIQUID_TYPE_SLIME))
    {
        if (res & LIQUID_MAP_UNDER_WATER)
            m_MirrorTimerFlags |= UNDERWATER_INWATER;
        else
            m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
    }

    // Allow travel in dark water on taxi or transport
    if ((liquid_status.type_flags & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
        m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
    else
        m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;

    // in lava check, anywhere in lava level
    if (liquid_status.type_flags & MAP_LIQUID_TYPE_MAGMA)
    {
        if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER | LIQUID_MAP_WATER_WALK))
            m_MirrorTimerFlags |= UNDERWATER_INLAVA;
        else
            m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
    }
    // in slime check, anywhere in slime level
    if (liquid_status.type_flags & MAP_LIQUID_TYPE_SLIME)
    {
        if (res & (LIQUID_MAP_UNDER_WATER | LIQUID_MAP_IN_WATER | LIQUID_MAP_WATER_WALK))
            m_MirrorTimerFlags |= UNDERWATER_INSLIME;
        else
            m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
    }
}

void Player::SetCanParry(bool value)
{
    if (m_canParry == value)
        return;

    m_canParry = value;
    UpdateParryPercentage();
}

void Player::SetCanBlock(bool value)
{
    if (m_canBlock == value)
        return;

    m_canBlock = value;
    UpdateBlockPercentage();
}

bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
{
    for (ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end(); ++itr)
        if (itr->pos == pos)
            return true;
    return false;
}

void Player::StopCastingBindSight()
{
    if (WorldObject* target = GetViewpoint())
    {
        if (target->isType(TYPEMASK_UNIT))
        {
            ((Unit*)target)->RemoveAurasByType(SPELL_AURA_BIND_SIGHT, GetGUID());
            ((Unit*)target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS, GetGUID());
            ((Unit*)target)->RemoveAurasByType(SPELL_AURA_MOD_POSSESS_PET, GetGUID());
        }
    }
}

void Player::SetViewpoint(WorldObject* target, bool apply)
{
    if (apply)
    {
        sLog->outDebug(LOG_FILTER_MAPS, "Player::CreateViewpoint: Player %s create seer %u (TypeId: %u).", GetName(), target->GetEntry(), target->GetTypeId());

        if (!AddGuidValue(PLAYER_FIELD_FARSIGHT_OBJECT, target->GetGUID()))
        {
            sLog->outFatal(LOG_FILTER_PLAYER, "Player::CreateViewpoint: Player %s cannot add new viewpoint!", GetName());
            return;
        }

        // farsight dynobj or puppet may be very far away
        UpdateVisibilityOf(target);

        if (target->isType(TYPEMASK_UNIT) && !GetVehicle())
            ((Unit*)target)->AddPlayerToVision(this);
    }
    else
    {
        sLog->outDebug(LOG_FILTER_MAPS, "Player::CreateViewpoint: Player %s remove seer", GetName());

        if (!RemoveGuidValue(PLAYER_FIELD_FARSIGHT_OBJECT, target->GetGUID()))
        {
            sLog->outFatal(LOG_FILTER_PLAYER, "Player::CreateViewpoint: Player %s cannot remove current viewpoint!", GetName());
            return;
        }

        if (target->isType(TYPEMASK_UNIT) && !GetVehicle())
            ((Unit*)target)->RemovePlayerFromVision(this);

        // Must immediately set seer back otherwise may crash
        m_seer = this;
    }
}

WorldObject* Player::GetViewpoint() const
{
    if (uint64 guid = GetGuidValue(PLAYER_FIELD_FARSIGHT_OBJECT))
        return (WorldObject*)ObjectAccessor::GetObjectByTypeMask(*this, guid, TYPEMASK_SEER);
    return NULL;
}

bool Player::CanUseBattlegroundObject()
{
    // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
    // maybe gameobject code should handle that ForceReaction usage
    // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
    return (//InBattleground() &&                          // in battleground - not need, check in other cases
             //!IsMounted() && - not correct, player is dismounted when he clicks on flag
             //player cannot use object when he is invulnerable (immune)
             !isTotalImmune() &&                            // not totally immune
             //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
             !HasStealthAura() &&                           // not stealthed
             !HasInvisibilityAura() &&                      // not invisible
             !HasAura(SPELL_RECENTLY_DROPPED_FLAG) &&    // can't pickup
             isAlive()                                      // live player
);
}

bool Player::CanCaptureTowerPoint()
{
    return (!HasStealthAura() &&                           // not stealthed
             !HasInvisibilityAura() &&                      // not invisible
             isAlive()                                      // live player
);
}

uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair, BarberShopStyleEntry const* newSkin, BarberShopStyleEntry const* p_NewFace /* = nullptr */)
{
    uint8 level = getLevel();

    if (level > GT_MAX_LEVEL)
        level = GT_MAX_LEVEL;                               // max level in this dbc
        
    uint8 skincolor     = GetByteValue(PLAYER_FIELD_HAIR_COLOR_ID, PLAYER_BYTES_OFFSET_SKIN_ID);
    uint8 l_Face        = GetByteValue(PLAYER_FIELD_HAIR_COLOR_ID, PLAYER_BYTES_OFFSET_FACE_ID);
    uint8 hairstyle     = GetByteValue(PLAYER_FIELD_HAIR_COLOR_ID, PLAYER_BYTES_OFFSET_HAIR_STYLE_ID);
    uint8 haircolor     = GetByteValue(PLAYER_FIELD_HAIR_COLOR_ID, PLAYER_BYTES_OFFSET_HAIR_COLOR_ID);
    uint8 facialhair    = GetByteValue(PLAYER_FIELD_REST_STATE, PLAYER_BYTES_2_OFFSET_FACIAL_STYLE);

    if ((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair) && (!newSkin || (newSkin->Data == skincolor)) && (!p_NewFace || (p_NewFace->Data == l_Face)))
        return 0;

    GtBarberShopCostBaseEntry const* bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);

    if (!bsc)                                                // shouldn't happen
        return 0xFFFFFFFF;

    float cost = 0;

    if (hairstyle != newhairstyle)
        cost += bsc->cost;                                  // full price

    if ((haircolor != newhaircolor) && (hairstyle == newhairstyle))
        cost += bsc->cost * 0.5f;                           // +1/2 of price

    if (facialhair != newfacialhair)
        cost += bsc->cost * 0.75f;                          // +3/4 of price

    if (newSkin && skincolor != newSkin->Data)
        cost += bsc->cost * 0.75f;                          // +5/6 of price

    if (p_NewFace && l_Face != p_NewFace->Data)
        cost += bsc->cost * 2;                              /// 2x price

    return uint32(cost);
}

void Player::InitGlyphsForLevel()
{
    uint32 slot = 0;
    // Hack fix to reorder glyphs
    if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(22))
        SetGlyphSlot(slot++, gs->Id);
    if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(21))
        SetGlyphSlot(slot++, gs->Id);
    for (uint32 i = 23; i < sGlyphSlotStore.GetNumRows() && slot < MAX_GLYPH_SLOT_INDEX; ++i)
        if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(i))
            SetGlyphSlot(slot++, gs->Id);

    uint8 level = getLevel();
    uint32 slotMask = 0;

    if (level >= 25)
        slotMask |= 0x01 | 0x02 | 0x40;
    if (level >= 50)
        slotMask |= 0x04 | 0x08 | 0x80;
    if (level >= 75)
        slotMask |= 0x10 | 0x20 | 0x100;

    SetUInt32Value(PLAYER_FIELD_GLYPH_SLOTS_ENABLED, slotMask);
}

bool Player::isTotalImmune()
{
    AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);

    uint32 immuneMask = 0;
    for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
    {
        immuneMask |= (*itr)->GetMiscValue();
        if (immuneMask & SPELL_SCHOOL_MASK_ALL)            // total immunity
            return true;
    }
    return false;
}

bool Player::HasTitle(uint32 bitIndex)
{
    if (bitIndex > MAX_TITLE_INDEX)
        return false;

    uint32 fieldIndexOffset = bitIndex / 32;
    uint32 flag = 1 << (bitIndex % 32);
    return HasFlag(PLAYER_FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
}

void Player::SetTitle(CharTitlesEntry const* title, bool lost)
{
    uint32 fieldIndexOffset = title->MaskID / 32;
    uint32 flag = 1 << (title->MaskID % 32);

    if (lost)
    {
        if (!HasFlag(PLAYER_FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
            return;

        RemoveFlag(PLAYER_FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
    }
    else
    {
        if (HasFlag(PLAYER_FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
            return;

        SetFlag(PLAYER_FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
    }

    if (lost)
    {
        WorldPacket data(SMSG_TITLE_LOST, 4);
        data << uint32(title->MaskID);
        GetSession()->SendPacket(&data);
    }
    else
    {
        WorldPacket data(SMSG_TITLE_EARNED, 4);
        data << uint32(title->MaskID);
        GetSession()->SendPacket(&data);
    }
}

bool Player::isTotalImmunity()<--- The function 'isTotalImmunity' is never used.
{
    AuraEffectList const& immune = GetAuraEffectsByType(SPELL_AURA_SCHOOL_IMMUNITY);

    for (AuraEffectList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
    {
        if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_ALL) !=0)   // total immunity
        {
            return true;
        }
        if (((*itr)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) !=0)   // physical damage immunity
        {
            for (AuraEffectList::const_iterator i = immune.begin(); i != immune.end(); ++i)
            {
                if (((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_MAGIC) !=0)   // magic immunity
                {
                    return true;
                }
            }
        }
    }
    return false;
}
/// @todo DO SOMETHING WITH THIS SHIT
                                   // Heurtoir,            Frappe héro,        Coup traumatisant
#define SPELL_WAR_ATTACK_LIST   47475,                  47450,              12809


                                // Consecration,       Repentir
#define SPELL_PAL_ATTACK_LIST   26573,              20066
                                // Eclair Lumineux,     Lumiere sacree
#define SPELL_PAL_FRIEND_LIST   48785,                  48782,              48785


                                // Tir des arcanes,     Morsure de serpent, Morsure de la mangouste
#define SPELL_HUNT_ATTACK_LIST  49045,                  49001,              53339


                                // pied,                Hemoragie           suriner         Eventail de couteaux
#define SPELL_ROG_ATTACK_LIST   1766,                   48660,              1776,           51723


                                // Douleur,             Chatiment,          Flammes sacrees
#define SPELL_PRI_ATTACK_LIST   48125,                  48123,              48135
                                // Soins rapides,       Rénovation,         Priere de guérison
#define SPELL_PRI_FRIEND_LIST   48071,                  48068,              48113


                                // frappe au coeur,     Toucher de glace,   Mort et decompo
#define SPELL_DK_ATTACK_LIST    55262,                  49909,              49938


                                // Chaine d'éclairs,    Horion de flammes,  Orage
#define SPELL_CHA_ATTACK_LIST   49271,                  49233,              59159
                                // Salve de guerison    Vague de soin       Bouclier de terre
#define SPELL_CHA_FRIEND_LIST   55459,                  49273,              49284


                                // Boule de feu,        Nova de givre,      Eclair de givrefeu
#define SPELL_MAG_ATTACK_LIST   42833,                  42917,              44614


                                // Immolation,          Drain de vie,       Hurlement de terreur
#define SPELL_DEM_ATTACK_LIST   47811,                  47857,              17928


                                // Colère,              Eclat Lunaire,      Lucioles
#define SPELL_DRU_ATTACK_LIST   48461,                  48463,              770
                                // Recuperation,        Toucher guerriseur, Tranquillité
#define SPELL_DRU_FRIEND_LIST   48441,                  48378,              48447
                                // Breath of fire       //Blackout kick     //Chi burst
#define SPELL_MONK_ATTACK_LIST  123725,                 128531,             130651

uint32 rand_number(uint32 value1, uint32 value2, uint32 value3 = 0, uint32 value4 = 0)
{
    switch (rand() % 4)
    {
        case 0:     return value1;
        case 1:     return value2;
        case 2:     return value3;
        case 3:     return value4;
        default:    return 0;
    }
}

void Player::UpdateCharmedAI()
{
    //This should only called in Player::Update
    Creature* charmer = GetCharmer()->ToCreature();

    //kill self if charm aura has infinite duration
    if (charmer->IsInEvadeMode())
    {
        AuraEffectList const& auras = GetAuraEffectsByType(SPELL_AURA_MOD_CHARM);
        for (AuraEffectList::const_iterator iter = auras.begin(); iter != auras.end(); ++iter)
            if ((*iter)->GetCasterGUID() == charmer->GetGUID() && (*iter)->GetBase()->IsPermanent())
            {
                charmer->DealDamage(this, GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
                return;
            }
    }

    if (!charmer->isInCombat())
        GetMotionMaster()->MoveFollow(charmer, PET_FOLLOW_DIST, PET_FOLLOW_ANGLE);

    Unit* target = getVictim();
    if (!target || !charmer->IsValidAttackTarget(target))
    {
        target = charmer->SelectNearestPlayerNotGM();
        if (!target)
            return;

        GetMotionMaster()->MoveChase(target);
        Attack(target, true);
    }
    else
    {
        if (HasUnitState(UNIT_STATE_CASTING))
            return;
        else if (target && GetMotionMaster()->GetCurrentMovementGeneratorType() != CHASE_MOTION_TYPE)
            GetMotionMaster()->MoveChase(target);

        // On laisse quelques attaques en melée deux fois sur trois
        if (urand(0, 2))
            return;

        // On s'arrete pour cast le spell
        GetMotionMaster()->MoveIdle();

        // 0 : Friendly, 1-2-3 : attack
        bool attack = urand(0 , 3);

        switch (getClass())
        {
            case CLASS_WARRIOR:
            {
                CastSpell(target, rand_number(SPELL_WAR_ATTACK_LIST));
                break;
            }
            case CLASS_PALADIN:
            {
                if (attack)
                    CastSpell(target, rand_number(SPELL_PAL_ATTACK_LIST));
                else
                    CastSpell(charmer, rand_number(SPELL_PAL_FRIEND_LIST));
                break;
            }
            case CLASS_HUNTER:
            {
                CastSpell(target, rand_number(SPELL_HUNT_ATTACK_LIST));
                break;
            }
            case CLASS_ROGUE:
            {
                CastSpell(target, rand_number(SPELL_ROG_ATTACK_LIST));
                break;
            }
            case CLASS_PRIEST:
            {
                if (attack)
                    CastSpell(target, rand_number(SPELL_PRI_ATTACK_LIST));
                else
                    CastSpell(charmer, rand_number(SPELL_PRI_FRIEND_LIST));
                break;
            }
            case CLASS_DEATH_KNIGHT:
            {
                CastSpell(target, rand_number(SPELL_DK_ATTACK_LIST));
                break;
            }
            case CLASS_SHAMAN:
            {
                if (attack)
                    CastSpell(target, rand_number(SPELL_CHA_ATTACK_LIST));
                else
                    CastSpell(charmer, rand_number(SPELL_CHA_FRIEND_LIST));
                break;
            }
            case CLASS_MAGE:
            {
                CastSpell(target, rand_number(SPELL_MAG_ATTACK_LIST));
                break;
            }
            case CLASS_WARLOCK:
            {
                CastSpell(target, rand_number(SPELL_DEM_ATTACK_LIST));
                break;
            }
            case CLASS_DRUID:
            {
                if (attack)
                    CastSpell(target, rand_number(SPELL_DRU_ATTACK_LIST));
                else
                    CastSpell(charmer, rand_number(SPELL_DRU_FRIEND_LIST));
                break;
            }
            case CLASS_MONK:
            {
                CastSpell(target, rand_number(SPELL_MONK_ATTACK_LIST));
                break;
            }
            default:
                break;
        }
    }
}

uint32 Player::GetRuneTypeBaseCooldown(RuneType runeType) const ///< runeType is unused
{
    float l_Cooldown = RUNE_BASE_COOLDOWN * GetFloatValue(UNIT_FIELD_MOD_HASTE_REGEN);
    float l_Modifier = 1.0f;

    AuraEffectList const& l_RegenAura = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
    for (AuraEffectList::const_iterator l_Idx = l_RegenAura.begin(); l_Idx != l_RegenAura.end(); ++l_Idx)
    {
        if ((*l_Idx)->GetMiscValue() == POWER_RUNES)
            l_Modifier += (float)(*l_Idx)->GetAmount() / 100.0f;
    }

    return l_Cooldown / l_Modifier;
}

void Player::RemoveRunesBySpell(uint32 spell_id)
{
    for (uint8 i = 0; i < MAX_RUNES; ++i)
    {
        if (m_runes.runes[i].spell_id == spell_id)
        {
            ConvertRune(i, GetBaseRune(i));
            SetRuneConvertSpell(i, 0);
        }
    }
}

void Player::RestoreBaseRune(uint8 index)
{
    ConvertRune(index, GetBaseRune(index));
    SetRuneConvertSpell(index, 0);
}

void Player::ConvertRune(uint8 p_Index, RuneType p_NewType)
{
    SetCurrentRune(p_Index, p_NewType);

    WorldPacket l_Data(SMSG_CONVERT_RUNE, 2);
    l_Data << uint8(p_Index);
    l_Data << uint8(p_NewType);

    GetSession()->SendPacket(&l_Data);
}

void Player::ResyncRunes(uint8 p_Count)
{
    WorldPacket l_Data(SMSG_RESYNC_RUNES, 4 + p_Count * 2);
    l_Data << uint32(p_Count);

    for (uint32 l_I = 0; l_I < p_Count; ++l_I)
    {
        l_Data << uint8(GetCurrentRune(l_I));                   // rune type
        l_Data << uint8(255 - (GetRuneCooldown(l_I) * 51));     // passed cooldown time (0-255)
    }

    GetSession()->SendPacket(&l_Data);
}

void Player::SendDeathRuneUpdate()
{
    if (getClass() != CLASS_DEATH_KNIGHT)
        return;

    for (uint8 l_I = 0; l_I < MAX_RUNES; ++l_I)
    {
        if (m_runes.runes[l_I].CurrentRune != RUNE_DEATH)
            continue;

        WorldPacket l_Data(SMSG_CONVERT_RUNE, 2);
        l_Data << uint8(l_I);
        l_Data << uint8(RUNE_DEATH);

        GetSession()->SendPacket(&l_Data);
    }
}

void Player::AddRunePower(uint8 index)<--- The function 'AddRunePower' is never used.
{
    WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
    data << uint32(1 << index);                             // mask (0x00-0x3F probably)
    GetSession()->SendPacket(&data);
}

static RuneType runeSlotTypes[MAX_RUNES] =
{
    /*0*/ RUNE_BLOOD,
    /*1*/ RUNE_BLOOD,
    /*2*/ RUNE_UNHOLY,
    /*3*/ RUNE_UNHOLY,
    /*4*/ RUNE_FROST,
    /*5*/ RUNE_FROST
};

void Player::InitRunes()
{
    if (getClass() != CLASS_DEATH_KNIGHT)
        return;

    m_runes.runeState = 0;

    for (uint8 i = 0; i < MAX_RUNES; ++i)
    {
        SetBaseRune(i, runeSlotTypes[i]);                              // init base types
        SetCurrentRune(i, runeSlotTypes[i]);                           // init current types
        SetRuneCooldown(i, 0);                                         // reset cooldowns
        SetRuneConvertSpell(i, 0);
        m_runes.SetRuneState(i);
        SetDeathRuneUsed(i, false);
    }

    UpdateAllRunesRegen();
    SetCurrentRuneForBloodTap(NUM_RUNE_TYPES);
}

bool Player::IsBaseRuneSlotsOnCooldown(RuneType runeType) const<--- The function 'IsBaseRuneSlotsOnCooldown' is never used.
{
    for (uint8 i = 0; i < MAX_RUNES; ++i)
        if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
            return false;

    return true;
}

void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
{
    Loot loot;
    loot.FillLoot (loot_id, store, this, true, true);

    uint32 max_slot = loot.GetMaxSlotInLootFor(this);
    for (uint32 i = 0; i < max_slot; ++i)
    {
        LootItem* lootItem = loot.LootItemInSlot(i, this);

        ItemPosCountVec dest;
        InventoryResult msg = CanStoreNewItem(bag, slot, dest, lootItem->itemid, lootItem->count);
        if (msg != EQUIP_ERR_OK && slot != NULL_SLOT)
            msg = CanStoreNewItem(bag, NULL_SLOT, dest, lootItem->itemid, lootItem->count);
        if (msg != EQUIP_ERR_OK && bag != NULL_BAG)
            msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, lootItem->itemid, lootItem->count);
        if (msg != EQUIP_ERR_OK)
        {
            SendEquipError(msg, NULL, NULL, lootItem->itemid);
            continue;
        }

        Item* pItem = StoreNewItem(dest, lootItem->itemid, true, lootItem->randomPropertyId);
        SendNewItem(pItem, lootItem->count, false, false, broadcast);
    }
}

void Player::StoreLootItem(uint8 lootSlot, Loot* loot, uint8 linkedLootSlot)
{
    QuestItem* qitem = NULL;
    QuestItem* ffaitem = NULL;
    QuestItem* conditem = NULL;
    QuestItem* currency = NULL;

    LootItem* item = loot->LootItemInSlot(lootSlot, this, &qitem, &ffaitem, &conditem, &currency);

    if (!item)
    {
        SendEquipError(EQUIP_ERR_LOOT_GONE, NULL, NULL);
        return;
    }

    if (item->alreadyAskedForRoll)
    {
        SendEquipError(EQUIP_ERR_LOOT_GONE, NULL, NULL);
        return;
    }

    // questitems use the blocked field for other purposes
    if (!qitem && item->is_blocked)
    {
        SendLootRelease(GetLootGUID());
        return;
    }

    if (currency)
    {
        if (CurrencyTypesEntry const * currencyEntry = sCurrencyTypesStore.LookupEntry(item->itemid))
            ModifyCurrency(item->itemid, int32(item->count * currencyEntry->GetPrecision()));

        SendNotifyLootItemRemoved(lootSlot);
        currency->is_looted = true;
        --loot->UnlootedCount;
        return;
    }

    ItemPosCountVec dest;
    InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, item->itemid, item->count);
    if (msg == EQUIP_ERR_OK)
    {
        AllowedLooterSet looters = item->GetAllowedLooters();
        Item* newitem = StoreNewItem(dest, item->itemid, true, item->randomPropertyId, looters);

        if (qitem)
        {
            qitem->is_looted = true;
            //freeforall is 1 if everyone's supposed to get the quest item.
            if (item->freeforall || loot->GetPlayerQuestItems().size() == 1)
                SendNotifyLootItemRemoved(linkedLootSlot == 0xFF ? lootSlot : linkedLootSlot);
            else
                loot->NotifyQuestItemRemoved(qitem->index);
        }
        else
        {
            if (ffaitem)
            {
                //freeforall case, notify only one player of the removal
                ffaitem->is_looted = true;
                SendNotifyLootItemRemoved(linkedLootSlot == 0xFF ? lootSlot : linkedLootSlot);
            }
            else
            {
                //not freeforall, notify everyone
                if (conditem)
                    conditem->is_looted = true;
                loot->NotifyItemRemoved(linkedLootSlot == 0xFF ? lootSlot : linkedLootSlot, item->PersonalLooter);
            }
        }

        //if only one person is supposed to loot the item, then set it to looted
        if (!item->freeforall)
            item->is_looted = true;

        --loot->UnlootedCount;

        /*if (const ItemTemplate* proto = sObjectMgr->GetItemTemplate(item->itemid))
            if (proto->Quality > ITEM_QUALITY_EPIC || (proto->Quality == ITEM_QUALITY_EPIC && proto->ItemLevel >= MinNewsItemLevel[sWorld->getIntConfig(CONFIG_EXPANSION)]))
                if (Guild* guild = sGuildMgr->GetGuildById(GetGuildId()))
                    guild->GetNewsLog().AddNewEvent(GUILD_NEWS_ITEM_LOOTED, time(NULL), GetGUID(), 0, item->itemid);*/


        /// Add bonus to item if needed
        if (newitem)
            newitem->AddItemBonuses(item->itemBonuses);

        ItemContext l_Context   = ItemContext::None;
        uint32 l_EncounterID    = 0;
        if (Creature* l_Creature = Creature::GetCreature(*this, loot->source))
        {
            if (InstanceScript* l_InstanceScript = l_Creature->GetInstanceScript())
                l_EncounterID = l_InstanceScript->GetEncounterIDForBoss(l_Creature);

            switch (GetMap()->GetDifficultyID())
            {
                case Difficulty::DifficultyRaidLFR:
                    l_Context = ItemContext::RaidLfr;
                    break;
                case Difficulty::DifficultyRaidNormal:
                    l_Context = ItemContext::RaidNormal;
                    break;
                case Difficulty::DifficultyRaidHeroic:
                    l_Context = ItemContext::RaidHeroic;
                    break;
                case Difficulty::DifficultyRaidMythic:
                    l_Context = ItemContext::RaidMythic;
                    break;
                case Difficulty::DifficultyNormal:
                    l_Context = ItemContext::DungeonNormal;
                    break;
                case Difficulty::DifficultyHeroic:
                    l_Context = ItemContext::DungeonHeroic;
                    break;
                case Difficulty::DifficultyMythic:
                    l_Context = ItemContext::DungeonMythic;
                    break;
                default:
                    break;
            }

            /// If item is not equipable, it doesn't need to be displayed
            /// If item is not from listed difficulties, it doesn't need to be displayed
            if ((newitem && !newitem->IsEquipable()) || l_Context == ItemContext::None)
            {
                l_EncounterID   = 0;
                l_Context       = ItemContext::None;
            }
        }

        SendNewItem(newitem, uint32(item->count), false, false, true, l_EncounterID, l_Context);

        /// Handle achievement criteria related to loot
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM, item->itemid, item->count);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE, loot->Type, item->count);
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM, item->itemid, item->count);

        /// Complete the tracking quest if needed
        AddTrackingQuestIfNeeded(loot->source);

        if (newitem)
            sScriptMgr->OnPlayerItemLooted(this, newitem);
    }
    else
        SendEquipError(msg, NULL, NULL, item->itemid);
}

void Player::AddTrackingQuestIfNeeded(uint64 p_SourceGuid)
{
    uint32 l_TrackingQuest = 0;

    /// If source is a creature
    if (IS_UNIT_GUID(p_SourceGuid))
    {
        Creature const* l_CreatureSource = sObjectAccessor->FindCreature(p_SourceGuid);
        if (l_CreatureSource == nullptr)
            return;

        l_TrackingQuest = l_CreatureSource->GetCreatureTemplate()->TrackingQuestID;
    }

    /// If source is a gameobject
    if (IS_GAMEOBJECT_GUID(p_SourceGuid))
    {
        GameObject const* l_GameObjectSource = sObjectAccessor->FindGameObject(p_SourceGuid);
        if (l_GameObjectSource == nullptr)
            return;

        l_TrackingQuest = l_GameObjectSource->GetGOInfo()->GetTrackingQuestId();
    }

    /// @TODO: Item can have tracking quest ?
    /// If someone as more informations, please tell me :D

    if (l_TrackingQuest == 0)
        return;

    auto l_Quest = sObjectMgr->GetQuestTemplate(l_TrackingQuest);
    if (l_Quest == nullptr)
        return;

    SetQuestStatus(l_Quest->GetQuestId(), QUEST_STATUS_COMPLETE);
    RewardQuest(l_Quest, 0, nullptr);
}

uint32 Player::CalculateTalentsPoints() const
{
    uint8 l_talentPoints = getLevel() / 15;

    // Should be a hardcoded value
    if (getLevel() == 100)
        ++l_talentPoints;

    return l_talentPoints;
}

bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone, uint32 spellId) const
{
    if (isGameMaster())
        return true;
    // Eye of the Storm is always allowed in Throne of the Four Winds
    if (zone == 5638 && spellId == 82724)
        return true;

    // Wings of Flame is always allowed in Firelands
    if (zone == 5723 && spellId == 98619)
        return true;

    // Tol Barad
    if (mapid == 732)
        return false;

    // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
    uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
    switch (v_map)
    {
        case 0:   // Eastern Kingdoms
            switch(zone)
            {
                // mapid of these zones is 530 but v_map is 0
                case 3430: // Eversong Woods
                case 3433: // Ghostlands
                case 4080: // Isle of Quel'Danas
                    return false;
            }
        // no break here
        case 1:   // Kalimdor
        case 646: // Deepholm
            return HasSpell(90267); // Flight Master's License
        case 571: // Northrend
            return HasSpell(54197); // Cold Weather Flying
        case 530: // Outland
        case 870: // Pandaria
            switch(zone)
            {
                case 6757: // Timeless Isle
                case 6661: // Isle of Giants
                    return false;
            }
            return true;
    }

    if (mapid == MS::Garrison::Globals::BaseMap || (m_Garrison && (mapid == (m_Garrison->GetGarrisonSiteLevelEntry() ? m_Garrison->GetGarrisonSiteLevelEntry()->MapID : -1) || (mapid == m_Garrison->GetShipyardMapId()))))
        return HasSpell(191645);    ///< Draenor Pathfinder

    return false;
}

void Player::learnSpellHighRank(uint32 spellid)
{
    learnSpell(spellid, false);

    if (uint32 next = sSpellMgr->GetNextSpellInChain(spellid))
        learnSpellHighRank(next);
}

void Player::_LoadSkills(PreparedQueryResult result)
{
    //                                                           0      1      2
    // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS,          "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));

    uint32 count = 0;
    uint8 professionCount = 0;
    if (result)
    {
        do
        {
            Field* fields = result->Fetch();
            uint16 skill    = fields[0].GetUInt16();
            uint16 value    = fields[1].GetUInt16();
            uint16 max      = fields[2].GetUInt16();

            /// Bug fixed in commit ed9e9fafb28bed40118a238849e0332726843cb6
            /// but we need to fix early learning of the last wod profession
            /// palier
            if (max == 675)
                max = 700;

            SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(skill);
            if (!pSkill)
            {
                PreparedStatement* l_Stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SKILL);
                l_Stmt->setUInt32(0, GetGUIDLow());
                l_Stmt->setUInt32(1, skill);
                CharacterDatabase.Execute(l_Stmt);

                sLog->outError(LOG_FILTER_PLAYER, "Character %u has skill %u that does not exist, delete it.", GetGUIDLow(), skill);
                continue;
            }

            // set fixed skill ranges
            switch (GetSkillRangeType(pSkill, false))
            {
                case SKILL_RANGE_LANGUAGE:                      // 300..300
                    value = max = 300;
                    break;
                case SKILL_RANGE_MONO:                          // 1..1, grey monolite bar
                    value = max = 1;
                    break;
                default:
                    break;
            }

            if (value == 0)
            {
                sLog->outError(LOG_FILTER_PLAYER, "Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
                PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_SKILL);
                stmt->setUInt32(0, GetGUIDLow());
                stmt->setUInt16(1, skill);
                CharacterDatabase.Execute(stmt);
                continue;
            }

            uint16 field = count / 2;
            uint8 offset = count & 1;

            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_LINEID + field, offset, skill);
            uint16 step = 0;

            if (pSkill->categoryId == SKILL_CATEGORY_SECONDARY || pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
            {
                if (max <= 600)
                    step = max / 75;
                else
                    step = (600 / 75) + ((max - 600) / 100);
            }

            if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
            {
                if (professionCount < DEFAULT_MAX_PRIMARY_TRADE_SKILL)
                    SetUInt32Value(PLAYER_FIELD_PROFESSION_SKILL_LINE + professionCount++, skill);
            }

            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_STEP + field, offset, step);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset, value);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset, max);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MODIFIER + field, offset, 0);
            SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT + field, offset, 0);

            mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
            learnSkillRewardedSpells(skill, value);

            ++count;

            if (count >= PLAYER_MAX_SKILLS)                      // client limit
            {
                sLog->outError(LOG_FILTER_PLAYER, "Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
                break;
            }
        }
        while (result->NextRow());
    }

    // Initialize unknow profession skill, needed since 5.4
    for (uint32 i = 0; i < sSkillLineStore.GetNumRows(); i++)
    {
        SkillLineEntry const* pSkill = sSkillLineStore.LookupEntry(i);
        if (!pSkill || (pSkill->id != 794 && pSkill->m_Flags != 0x1080))
            continue;

        if (HasSkill(i))
            continue;

        uint16 value = 0;
        uint16 max = 0;
        uint16 step = 0;

        uint16 field = count / 2;
        uint8 offset = count & 1;

        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_LINEID + field, offset, i);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_STEP + field, offset, step);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset, value);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset, max);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MODIFIER + field, offset, 0);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT + field, offset, 0);

        ++count;

        if (count >= PLAYER_MAX_SKILLS)                      // client limit
        {
            sLog->outError(LOG_FILTER_PLAYER, "Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
            break;
        }
    }

    for (; count < PLAYER_MAX_SKILLS; ++count)
    {
        uint16 field = count / 2;
        uint8 offset = count & 1;

        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_LINEID + field, offset, 0);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_STEP + field, offset, 0);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_RANK + field, offset, 0);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MAX_RANK + field, offset, 0);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_MODIFIER + field, offset, 0);
        SetUInt16Value(PLAYER_FIELD_SKILL + SKILL_OFFSET_TALENT + field, offset, 0);
    }

    // special settings
    if (getClass() == CLASS_DEATH_KNIGHT)
    {
        uint8 base_level = std::min(getLevel(), uint8(sWorld->getIntConfig(CONFIG_START_HEROIC_PLAYER_LEVEL)));
        if (base_level < 1)
            base_level = 1;
        uint16 base_skill = (base_level-1)*5;               // 270 at starting level 55
        if (base_skill < 1)
            base_skill = 1;                                 // skill mast be known and then > 0 in any case

        if (GetPureSkillValue(SKILL_FIRST_AID) < base_skill)
            SetSkill(SKILL_FIRST_AID, 0, base_skill, base_skill);
        if (GetPureSkillValue(SKILL_AXES) < base_skill)
            SetSkill(SKILL_AXES, 0, base_skill, base_skill);
        if (GetPureSkillValue(SKILL_DEFENSE) < base_skill)
            SetSkill(SKILL_DEFENSE, 0, base_skill, base_skill);
        if (GetPureSkillValue(SKILL_POLEARMS) < base_skill)
            SetSkill(SKILL_POLEARMS, 0, base_skill, base_skill);
        if (GetPureSkillValue(SKILL_SWORDS) < base_skill)
            SetSkill(SKILL_SWORDS, 0, base_skill, base_skill);
        if (GetPureSkillValue(SKILL_2H_AXES) < base_skill)
            SetSkill(SKILL_2H_AXES, 0, base_skill, base_skill);
        if (GetPureSkillValue(SKILL_2H_SWORDS) < base_skill)
            SetSkill(SKILL_2H_SWORDS, 0, base_skill, base_skill);
        if (GetPureSkillValue(SKILL_UNARMED) < base_skill)
            SetSkill(SKILL_UNARMED, 0, base_skill, base_skill);
    }
}

InventoryResult Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
{
    ItemTemplate const* pProto = pItem->GetTemplate();

    // proto based limitations
    if (InventoryResult res = CanEquipUniqueItem(pProto, eslot, limit_count))
        return res;

    // check unique-equipped on gems
    for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
    {
        uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
        if (!enchant_id)
            continue;
        SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
        if (!enchantEntry)
            continue;

        ItemTemplate const* pGem = sObjectMgr->GetItemTemplate(enchantEntry->GemID);
        if (!pGem)
            continue;

        // include for check equip another gems with same limit category for not equipped item (and then not counted)
        uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
            ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;

        if (InventoryResult res = CanEquipUniqueItem(pGem, eslot, gem_limit_count))
            return res;
    }

    return EQUIP_ERR_OK;
}

InventoryResult Player::CanEquipUniqueItem(ItemTemplate const* itemProto, uint8 except_slot, uint32 limit_count) const
{
    // check unique-equipped on item
    if (itemProto->Flags & ITEM_FLAG_UNIQUE_EQUIPPED)
    {
        // there is an equip limit on this item
        if (HasItemOrGemWithIdEquipped(itemProto->ItemId, 1, except_slot))
            return EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE;
    }

    // check unique-equipped limit
    if (itemProto->ItemLimitCategory)
    {
        ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
        if (!limitEntry)
            return EQUIP_ERR_NOT_EQUIPPABLE;

        // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case

        if (limit_count > limitEntry->maxCount)
            return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS;

        // there is an equip limit on this item
        if (HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory, limitEntry->maxCount - limit_count + 1, except_slot))
            return EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED;
    }

    return EQUIP_ERR_OK;
}

void Player::HandleFall(MovementInfo const& movementInfo)
{
    // calculate total z distance of the fall
    float z_diff = m_lastFallZ - movementInfo.pos.GetPositionZ();
    //sLog->outDebug(LOG_FILTER_GENERAL, "zDiff = %f", z_diff);

    //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
    // 14.57 can be calculated by resolving damageperc formula below to 0
    if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
        !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
        !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) &&
        !(getClass() == CLASS_DEATH_KNIGHT && HasAura(59307) && HasAura(3714)))
    {
        //Safe fall, fall height reduction
        int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);

        // Glyph of Safe Fall
        if (HasAura(58033) && HasAura(1860))
            safe_fall += 10;

        float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;

        if (damageperc > 0)
        {
            uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld->getRate(RATE_DAMAGE_FALL));

            float height = movementInfo.pos.m_positionZ;
            UpdateGroundPositionZ(movementInfo.pos.m_positionX, movementInfo.pos.m_positionY, height);

            if (damage > 0)
            {
                //Prevent fall damage from being more than the player maximum health
                if (damage > GetMaxHealth())
                    damage = GetMaxHealth();

                // Gust of Wind
                if (HasAura(43621))
                    damage = GetMaxHealth()/2;

                uint32 original_health = GetHealth();
                uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);

                // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
                if (isAlive() && final_damage < original_health)
                    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
            }

            //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
            sLog->outDebug(LOG_FILTER_PLAYER, "FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d", movementInfo.pos.GetPositionZ(), height, GetPositionZ(), movementInfo.fallTime, height, damage, safe_fall);
        }
    }
    RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_LANDING); // No fly zone - Parachute

    /// Handler for Disengage, should give Posthaste just after landing
    /// If in future we have some spells with same mechanic, just need to add switch
    if (getClass() == CLASS_HUNTER && GetLastUsedLeapBackSpell() == 56446 && HasAura(109215))
        CastSpell(this, 118922, true);

    ClearLastUsedLeapBackSpell();
}

void Player::UpdateAchievementCriteria(AchievementCriteriaTypes p_Type, uint64 p_MiscValue1 /*= 0*/, uint64 p_MiscValue2 /*= 0*/, uint64 p_MiscValue3 /*= 0*/, Unit* p_Unit /*= nullptr*/, bool p_LoginCheck /*= false*/)
{
    if (sWorld->getBoolConfig(CONFIG_ACHIEVEMENT_DISABLE))
        return;

    AchievementCriteriaUpdateTask l_Task;
    l_Task.PlayerGUID = GetGUID();
    l_Task.UnitGUID   = p_Unit ? p_Unit->GetGUID() : 0;
    l_Task.Task = [p_Type, p_MiscValue1, p_MiscValue2, p_MiscValue3, p_LoginCheck](uint64 const& p_PlayerGuid, uint64 const& p_UnitGUID) -> void
    {
        /// Task will be executed async
        /// We need to ensure the player still exist
        Player* l_Player = HashMapHolder<Player>::Find(p_PlayerGuid);
        if (l_Player == nullptr)
            return;

        /// Same for the unit
        Unit* l_Unit = p_UnitGUID ? Unit::GetUnit(*l_Player, p_UnitGUID) : nullptr;

        l_Player->GetAchievementMgr().UpdateAchievementCriteria(p_Type, p_MiscValue1, p_MiscValue2, p_MiscValue3, l_Unit, l_Player, p_LoginCheck);

        // Update only individual achievement criteria here, otherwise we may get multiple updates
        // from a single boss kill
        if (sAchievementMgr->IsGroupCriteriaType(p_Type))
            return;

        if (Guild* l_Guild = sGuildMgr->GetGuildById(l_Player->GetGuildId()))
            l_Guild->GetAchievementMgr().UpdateAchievementCriteria(p_Type, p_MiscValue1, p_MiscValue2, p_MiscValue3, l_Unit, l_Player, p_LoginCheck);
        
    };

    sAchievementMgr->AddCriteriaUpdateTask(l_Task);
}

void Player::CompletedAchievement(AchievementEntry const* entry)
{
    GetAchievementMgr().CompletedAchievement(entry, this);
}

static const uint8 k_LevelPerTier[7] =
{
    15,
    30,
    45,
    60,
    75,
    90,
    100
};

bool Player::LearnTalent(uint32 talentId)
{
    uint32 CurTalentPoints = GetFreeTalentPoints();
    if (CurTalentPoints == 0)
        return false;

    TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
    if (!talentInfo)
        return false;

    if (k_LevelPerTier[talentInfo->TierID] > getLevel())
        return false;

    if (talentInfo->ClassID != getClass())
        return false;

    uint32 spellid = talentInfo->SpellID;
    if (spellid == 0)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Talent.dbc have for talent: %uspell id = 0", talentId);
        return false;
    }

    // already known
    if (HasSpell(spellid))
        return false;

    // Check if players has already learn a talent for this rank
    for (uint32 i = 0; i < sTalentStore.GetNumRows(); i++)
    {
        TalentEntry const* tInfo = sTalentStore.LookupEntry(i);
        if (!tInfo)
            continue;

        if (tInfo->ClassID != getClass())
            continue;

        if (tInfo->TierID == talentInfo->TierID && HasSpell(tInfo->SpellID))
            return false;
    }

    // learn! (other talent ranks will unlearned at learning)
    learnSpell(spellid, false);
    AddTalent(spellid, GetActiveSpec(), true);
    CastPassiveTalentSpell(spellid);

    sLog->outInfo(LOG_FILTER_GENERAL, "TalentID: %u Spell: %u Spec: %u\n", talentId, spellid, GetActiveSpec());
    return true;
}

void Player::AddKnownCurrency(uint32 itemId)<--- The function 'AddKnownCurrency' is never used.
{
    if (CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
        SetFlag64(0, (1LL << (ctEntry->ID-1)));
}

void Player::UpdateFallInformationIfNeed(MovementInfo const& minfo, uint16 opcode)
{
    if (m_lastFallTime >= minfo.fallTime || m_lastFallZ <= minfo.pos.GetPositionZ() || opcode == CMSG_MOVE_FALL_LAND)
        SetFallInformation(minfo.fallTime, minfo.pos.GetPositionZ());
}

void Player::UnsummonPetTemporaryIfAny()
{
    Pet* pet = GetPet();
    if (!pet)
        return;

    if (!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned())
    {
        m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
        m_oldpetspell = pet->GetUInt32Value(UNIT_FIELD_CREATED_BY_SPELL);
    }

    RemovePet(pet, PET_SLOT_ACTUAL_PET_SLOT, false, pet->m_Stampeded);
}

void Player::ResummonPetTemporaryUnSummonedIfAny()
{
    if (!m_temporaryUnsummonedPetNumber)
        return;

    // not resummon in not appropriate state
    if (IsPetNeedBeTemporaryUnsummoned())
        return;

    if (GetPetGUID())
        return;

    Pet*   l_NewPet     = new Pet(this);
    uint64 l_PlayerGUID = GetGUID();
    uint32 l_PetNumber  = m_temporaryUnsummonedPetNumber;

    PreparedStatement* l_PetStatement = PetQueryHolder::GenerateFirstLoadStatement(0, m_temporaryUnsummonedPetNumber, GetGUIDLow(), true, PET_SLOT_UNK_SLOT);
    CharacterDatabase.AsyncQuery(l_PetStatement, [l_NewPet, l_PlayerGUID, l_PetNumber](PreparedQueryResult p_Result) -> void
    {
        if (!p_Result)
        {
            delete l_NewPet;
            return;
        }

        PetQueryHolder* l_PetHolder = new PetQueryHolder(p_Result->Fetch()[0].GetUInt32(), p_Result);
        l_PetHolder->Initialize();

        auto l_QueryHolderResultFuture = CharacterDatabase.DelayQueryHolder(l_PetHolder);

        sWorld->AddQueryHolderCallback(QueryHolderCallback(l_QueryHolderResultFuture, [l_NewPet, l_PlayerGUID, l_PetNumber](SQLQueryHolder* p_QueryHolder) -> void
        {
            Player* l_Player = sObjectAccessor->FindPlayer(l_PlayerGUID);
            if (!l_Player || !p_QueryHolder || l_Player != l_NewPet->GetOwner())
            {
                delete l_NewPet;
                return;
            }

            l_NewPet->LoadPetFromDB(l_Player, 0, l_PetNumber, true, PET_SLOT_UNK_SLOT, false, (PetQueryHolder*)p_QueryHolder, [](Pet* p_Pet, bool p_Result)
            {
                if (!p_Result)
                {
                    delete p_Pet;
                    return;
                }

                Player* l_Player = p_Pet->GetOwner();
                if (l_Player == nullptr)
                    return;

                if (l_Player->HasSpell(109212) && !l_Player->HasAura(118694))
                    l_Player->CastSpell(l_Player, 118694, true);
            });
        }));
    });

    m_temporaryUnsummonedPetNumber = 0;
}

bool Player::canSeeSpellClickOn(Creature const* c) const
{
    SpellClickInfoMapBounds clickPair = sObjectMgr->GetSpellClickInfoMapBounds(c->GetEntry());
    if (clickPair.first == clickPair.second)
        return true;

    for (SpellClickInfoContainer::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
    {
        if (!itr->second.IsFitToRequirements(this, c))
            return false;

        if (!sConditionMgr->IsObjectMeetingSpellClickConditions(c->GetEntry(), itr->second.spellId, const_cast<Player*>(this), const_cast<Creature*>(c)))
            return false;
    }

    return true;
}

void Player::BuildPlayerTalentsInfoData(WorldPacket * p_Data)
{
    uint8 l_SpeCount = GetSpecsCount();

    if (l_SpeCount > MAX_TALENT_SPECS)
        SetSpecsCount(MAX_TALENT_SPECS);

    *p_Data << uint8(GetActiveSpec());
    *p_Data << uint32(l_SpeCount);

    for (uint8 l_SpeIT = 0; l_SpeIT < l_SpeCount; ++l_SpeIT)
    {
        PlayerTalentMap & l_PlayerTalent = *GetTalentMap(l_SpeIT);
        ByteBuffer l_Talents(400);
        int l_TalentCount = 0;

        for (PlayerTalentMap::iterator itr = l_PlayerTalent.begin(); itr != l_PlayerTalent.end(); ++itr)
        {
            SpellInfo const* l_SpellInfo = sSpellMgr->GetSpellInfo((*itr).first);

            if (l_SpellInfo && !l_SpellInfo->m_TalentIDs.empty() && itr->second->state != PLAYERSPELL_REMOVED)
            {
                uint32 l_SpecID = GetSpecializationId();
                uint16 l_Talent = 0;

                for (uint32 l_TalentID : l_SpellInfo->m_TalentIDs)
                {
                    if (TalentEntry const* l_TalentEntry = sTalentStore.LookupEntry(l_TalentID))
                    {
                        if (l_TalentEntry->SpecID == l_SpecID)
                        {
                            l_Talent = l_TalentID;
                            break;
                        }

                        l_Talent = l_TalentID;
                    }
                }

                l_Talents << uint16(l_Talent);
                l_TalentCount++;
            }
        }

        *p_Data << uint32(GetSpecializationId(l_SpeIT));
        *p_Data << uint32(l_TalentCount);

        for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
            *p_Data << uint16(GetGlyph(l_SpeIT, i));

        p_Data->append(l_Talents);
    }
}

void Player::SendTalentsInfoData(bool pet)
{
    if (pet)
    {
        Pet* pPet = GetPet();
        WorldPacket data(SMSG_SET_PET_SPECIALIZATION);
        data << uint16(pPet ? pPet->GetSpecializationId() : 0);     ///< SpecId
        GetSession()->SendPacket(&data);
        return;
    }

    // Update free talents points client-side
    SetUInt32Value(PLAYER_FIELD_MAX_TALENT_TIERS, CalculateTalentsPoints());

    WorldPacket data(SMSG_UPDATE_TALENT_DATA);
    BuildPlayerTalentsInfoData(&data);
    GetSession()->SendPacket(&data);
}

void Player::SendTalentsInvoluntarilyReset(bool p_IsPet /*= false*/)
{
    WorldPacket l_Data(Opcodes::SMSG_TALENTS_INVOLUNTARILY_RESET, 1);
    l_Data.WriteBit(p_IsPet);
    l_Data.FlushBits();
    GetSession()->SendPacket(&l_Data);
}

void Player::BuildEnchantmentsInfoData(WorldPacket* data)<--- The function 'BuildEnchantmentsInfoData' is never used.
{
    uint32 slotUsedMask = 0;
    size_t slotUsedMaskPos = data->wpos();
    *data << uint32(slotUsedMask);                          // slotUsedMask < 0x80000

    for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
    {
        Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);

        if (!item)
            continue;

        slotUsedMask |= (1 << i);

        *data << uint32(item->GetEntry());                  // item entry

        uint16 enchantmentMask = 0;
        size_t enchantmentMaskPos = data->wpos();
        *data << uint16(enchantmentMask);                   // enchantmentMask < 0x1000

        for (uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
        {
            uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));

            if (!enchId)
                continue;

            enchantmentMask |= (1 << j);

            *data << uint16(enchId);                        // enchantmentId?
        }

        data->put<uint16>(enchantmentMaskPos, enchantmentMask);

        *data << uint16(0);                                 // unknown
        data->appendPackGUID(item->GetGuidValue(ITEM_FIELD_CREATOR)); // item creator
        *data << uint32(0);                                 // seed?
    }

    data->put<uint32>(slotUsedMaskPos, slotUsedMask);
}

void Player::SendEquipmentSetList()
{
    uint32 l_EquipmentSetCount = 0;

    WorldPacket l_Data(SMSG_EQUIPMENT_SET_LIST, 4 * 1024);

    for (EquipmentSets::iterator l_Itr = m_EquipmentSets.begin(); l_Itr != m_EquipmentSets.end(); ++l_Itr)
    {
        if (l_Itr->second.state == EQUIPMENT_SET_DELETED)
            continue;

        ++l_EquipmentSetCount;
    }

    l_Data << uint32(l_EquipmentSetCount);

    for (EquipmentSets::iterator l_Itr = m_EquipmentSets.begin(); l_Itr != m_EquipmentSets.end(); ++l_Itr)
    {
        if (l_Itr->second.state == EQUIPMENT_SET_DELETED)
            continue;

        l_Data << uint64(l_Itr->second.Guid);   ///< Guid
        l_Data << uint32(l_Itr->first);
        l_Data << uint32(0);

        for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
        {
            // ignored slots stored in IgnoreMask, client wants "1" as raw GUID, so no HIGHGUID_ITEM
            if (l_Itr->second.IgnoreMask & (1 << i))
                l_Data.appendPackGUID(0);
            else
                l_Data.appendPackGUID(MAKE_NEW_GUID(l_Itr->second.Items[i], 0, HIGHGUID_ITEM));
        }

        l_Data.WriteBits(l_Itr->second.Name.size(), 8);
        l_Data.WriteBits(l_Itr->second.IconName.size(), 9);
        l_Data.FlushBits();

        l_Data.WriteString(l_Itr->second.Name);
        l_Data.WriteString(l_Itr->second.IconName);
    }

    GetSession()->SendPacket(&l_Data);
}

void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
{
    if (eqset.Guid != 0)
    {
        bool found = false;

        for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
        {
            if ((itr->second.Guid == eqset.Guid) && (itr->first == index))
            {
                found = true;
                break;
            }
        }

        if (!found)                                          // something wrong...
        {
            sLog->outError(LOG_FILTER_PLAYER, "Player %s tried to save equipment set " UI64FMTD " (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
            return;
        }
    }

    EquipmentSet& eqslot = m_EquipmentSets[index];

    EquipmentSetUpdateState old_state = eqslot.state;

    eqslot = eqset;

    if (eqset.Guid == 0)
        eqslot.Guid = sObjectMgr->GenerateEquipmentSetGuid();

    eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
}

void Player::_SaveEquipmentSets(SQLTransaction& trans)
{
    for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
    {
        uint32 index = itr->first;
        EquipmentSet& eqset = itr->second;
        PreparedStatement* stmt = NULL;
        uint8 j = 0;
        switch (eqset.state)
        {
            case EQUIPMENT_SET_UNCHANGED:
                ++itr;
                break;                                      // nothing do
            case EQUIPMENT_SET_CHANGED:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_EQUIP_SET);
                stmt->setString(j++, eqset.Name.c_str());
                stmt->setString(j++, eqset.IconName.c_str());
                stmt->setUInt32(j++, eqset.IgnoreMask);
                for (uint8 i=0; i<EQUIPMENT_SLOT_END; ++i)
                    stmt->setUInt32(j++, eqset.Items[i]);
                stmt->setUInt32(j++, GetGUIDLow());
                stmt->setUInt64(j++, eqset.Guid);
                stmt->setUInt32(j, index);
                trans->Append(stmt);
                eqset.state = EQUIPMENT_SET_UNCHANGED;
                ++itr;
                break;
            case EQUIPMENT_SET_NEW:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_EQUIP_SET);
                stmt->setUInt32(j++, GetGUIDLow());
                stmt->setUInt64(j++, eqset.Guid);
                stmt->setUInt32(j++, index);
                stmt->setString(j++, eqset.Name.c_str());
                stmt->setString(j++, eqset.IconName.c_str());
                stmt->setUInt32(j++, eqset.IgnoreMask);
                for (uint8 i=0; i<EQUIPMENT_SLOT_END; ++i)
                    stmt->setUInt32(j++, eqset.Items[i]);
                trans->Append(stmt);
                eqset.state = EQUIPMENT_SET_UNCHANGED;
                ++itr;
                break;
            case EQUIPMENT_SET_DELETED:
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EQUIP_SET);
                stmt->setUInt64(0, eqset.Guid);
                trans->Append(stmt);
                m_EquipmentSets.erase(itr++);
                break;
        }
    }
}

void Player::_SaveArenaData(SQLTransaction& trans)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHARACTER_ARENA_DATA);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);

    stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHARACTER_ARENA_DATA);
    stmt->setUInt32(0, GetGUIDLow());

    uint8 j = 1;
    for (uint8 i = 0; i < MAX_PVP_SLOT; ++i)
    {
        stmt->setUInt32(j++, m_ArenaPersonalRating[i]);
        stmt->setUInt32(j++, m_BestRatingOfWeek[i]);
        stmt->setUInt32(j++, m_BestRatingOfSeason[i]);
        stmt->setInt32(j++, m_ArenaMatchMakerRating[i]);
        stmt->setUInt32(j++, m_WeekGames[i]);
        stmt->setUInt32(j++, m_WeekWins[i]);
        stmt->setUInt32(j++, m_PrevWeekWins[i]);
        stmt->setUInt32(j++, m_PrevWeekGames[i]);
        stmt->setUInt32(j++, m_SeasonGames[i]);
        stmt->setUInt32(j++, m_SeasonWins[i]);
    }
    trans->Append(stmt);
}

void Player::_SaveBGData(SQLTransaction& trans)
{
    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_PLAYER_BGDATA);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);
    /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell, lastActiveSpec, lastSpecId */
    stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_PLAYER_BGDATA);
    stmt->setUInt32(0, GetGUIDLow());
    stmt->setUInt32(1, m_bgData.bgInstanceID);
    stmt->setUInt16(2, m_bgData.bgTeam);
    stmt->setFloat (3, m_bgData.joinPos.GetPositionX());
    stmt->setFloat (4, m_bgData.joinPos.GetPositionY());
    stmt->setFloat (5, m_bgData.joinPos.GetPositionZ());
    stmt->setFloat (6, m_bgData.joinPos.GetOrientation());
    stmt->setUInt16(7, m_bgData.joinPos.GetMapId());
    stmt->setUInt16(8, m_bgData.taxiPath[0]);
    stmt->setUInt16(9, m_bgData.taxiPath[1]);
    stmt->setUInt16(10, m_bgData.mountSpell);
    stmt->setUInt8(11, m_bgData.m_LastActiveSpec);
    trans->Append(stmt);
}

void Player::DeleteEquipmentSet(uint64 setGuid)
{
    for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
    {
        if (itr->second.Guid == setGuid)
        {
            if (itr->second.state == EQUIPMENT_SET_NEW)
                m_EquipmentSets.erase(itr);
            else
                itr->second.state = EQUIPMENT_SET_DELETED;
            break;
        }
    }
}

void Player::RemoveAtLoginFlag(AtLoginFlags flags, bool persist /*= false*/)
{
    m_atLoginFlags &= ~flags;

    if (persist)
    {
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_REM_AT_LOGIN_FLAG);

        stmt->setUInt16(0, uint16(flags));
        stmt->setUInt32(1, GetGUIDLow());

        CharacterDatabase.Execute(stmt);
    }
}

void Player::SendClearCooldown(uint32 p_SpellID, Unit* p_Target, bool p_ClearOnHold)
{
    WorldPacket l_Data(SMSG_CLEAR_COOLDOWN);

    l_Data << uint32(p_SpellID);
    l_Data.WriteBit(p_ClearOnHold);
    l_Data.WriteBit(p_Target == GetPet());             ///< IsPetCooldown
    l_Data.FlushBits();

    SendDirectMessage(&l_Data);
}

void Player::ResetMap()
{
    // this may be called during Map::Update
    // after decrement+unlink, ++m_mapRefIter will continue correctly
    // when the first element of the list is being removed
    // nocheck_prev will return the padding element of the RefManager
    // instead of NULL in the case of prev
    GetMap()->UpdateIteratorBack(this);
    Unit::ResetMap();
    GetMapRef().unlink();
}

void Player::SetMap(Map* map)
{
    Unit::SetMap(map);
    m_mapRef.link(map, this);
}

void Player::_LoadGlyphs(PreparedQueryResult result)
{
    // SELECT spec, glyph1, glyph2, glyph3, glyph4, glyph5, glyph6 FROM character_glyphs WHERE guid = '%u'
    if (!result)
        return;

    do
    {
        Field* fields = result->Fetch();

        uint8 spec = fields[0].GetUInt8();
        if (spec >= GetSpecsCount())
            continue;

        for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
            _talentMgr->SpecInfo[spec].Glyphs[i] = fields[i + 1].GetUInt16();
    }
    while (result->NextRow());

    m_glyphsChanged = false;
}

void Player::_SaveGlyphs(SQLTransaction& trans)
{
    if (!m_glyphsChanged)
        return;

    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_GLYPHS);
    stmt->setUInt32(0, GetGUIDLow());
    trans->Append(stmt);

    for (uint8 spec = 0; spec < GetSpecsCount(); ++spec)
    {
        uint8 index = 0;

        stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_GLYPHS);
        stmt->setUInt32(index++, GetGUIDLow());

        stmt->setUInt8(index++, spec);

        for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
            stmt->setUInt16(index++, uint16(GetGlyph(spec, i)));

        trans->Append(stmt);
    }

    m_glyphsChanged = false;
}

void Player::_LoadTalents(PreparedQueryResult result)
{
    // SetPQuery(PLAYER_LOGIN_QUERY_LOADTALENTS, "SELECT spell, spec FROM character_talent WHERE guid = '%u'", GUID_LOPART(m_guid));
    if (result)
    {
        do
            AddTalent((*result)[0].GetUInt32(), (*result)[1].GetUInt8(), false);
        while (result->NextRow());
    }
}

void Player::_SaveTalents(SQLTransaction& trans)
{
    PreparedStatement* stmt = NULL;

    for (uint8 i = 0; i < MAX_TALENT_SPECS; ++i)
    {
        for (PlayerTalentMap::iterator itr = GetTalentMap(i)->begin(); itr != GetTalentMap(i)->end();)
        {
            if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
            {
                stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_TALENT_BY_SPELL_SPEC);
                stmt->setUInt32(0, GetGUIDLow());
                stmt->setUInt32(1, itr->first);
                stmt->setUInt8(2, itr->second->spec);
                trans->Append(stmt);
            }

            if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
            {
                if (itr->second->spec > 1)
                {
                    sLog->outAshran("Invalid spec index (%d > 1) on player %s (%ull), not saving talent to prevent crash at loading", itr->second->spec, m_name.c_str(), GetGUID());
                    continue;
                }

                stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_TALENT);
                stmt->setUInt32(0, GetGUIDLow());
                stmt->setUInt32(1, itr->first);
                stmt->setUInt8(2, itr->second->spec);
                trans->Append(stmt);
            }

            if (itr->second->state == PLAYERSPELL_REMOVED)
            {
                delete itr->second;
                GetTalentMap(i)->erase(itr++);
            }
            else
            {
                itr->second->state = PLAYERSPELL_UNCHANGED;
                ++itr;
            }
        }
    }
}

void Player::UpdateSpecCount(uint8 count)
{
    uint32 curCount = GetSpecsCount();
    if (curCount == count)
        return;

    if (GetActiveSpec() >= count)
        ActivateSpec(0);

    SQLTransaction trans = CharacterDatabase.BeginTransaction();
    PreparedStatement* stmt = NULL;

    // Copy spec data
    if (count > curCount)
    {
        _SaveActions(trans); // make sure the button list is cleaned up
        for (ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); ++itr)
        {
            stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_CHAR_ACTION);
            stmt->setUInt32(0, GetGUIDLow());
            stmt->setUInt8(1, 1);
            stmt->setUInt8(2, itr->first);
            stmt->setUInt32(3, itr->second.GetAction());
            stmt->setUInt8(4, uint8(itr->second.GetType()));
            trans->Append(stmt);
        }
    }
    // Delete spec data for removed spec.
    else if (count < curCount)
    {
        _SaveActions(trans);

        stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACTION_EXCEPT_SPEC);
        stmt->setUInt8(0, GetActiveSpec());
        stmt->setUInt32(1, GetGUIDLow());
        trans->Append(stmt);

    }

    CharacterDatabase.CommitTransaction(trans);

    SetSpecsCount(count);

    SendTalentsInfoData(false);
}

void Player::ActivateSpec(uint8 spec)
{
    if (GetActiveSpec() == spec)
        return;

    if (spec > GetSpecsCount())
        return;

    if (IsNonMeleeSpellCasted(false))
        InterruptNonMeleeSpells(false);

    SQLTransaction trans = CharacterDatabase.BeginTransaction();
    _SaveActions(trans);
    CharacterDatabase.CommitTransaction(trans);

    // TO-DO: We need more research to know what happens with warlock's reagent
    if (Pet* pet = GetPet())
        RemovePet(pet, PET_SLOT_ACTUAL_PET_SLOT, true, pet->m_Stampeded);

    ClearComboPoints();
    ClearAllReactives();
    UnsummonAllTotems();
    RemoveAllControlled();
    RemoveAllAurasOnDeath();
    if (GetPet())
        GetPet()->RemoveAllAurasOnDeath();

    //RemoveAllAuras(GetGUID(), NULL, false, true); // removes too many auras
    //ExitVehicle(); // should be impossible to switch specs from inside a vehicle..

    // Let client clear his current Actions
    SendActionButtons(2);
    // m_actionButtons.clear() is called in the next _LoadActionButtons

    for (auto itr : *GetTalentMap(GetActiveSpec()))
    {
        removeSpell(itr.first, true); // removes the talent, and all dependant, learned, and chained spells..
        if (const SpellInfo* _spellEntry = sSpellMgr->GetSpellInfo(itr.first))
        {
            for (uint8 i = 0; i < _spellEntry->EffectCount; ++i)                  // search through the SpellInfo for valid trigger spells
                if (_spellEntry->Effects[i].TriggerSpell > 0 && _spellEntry->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL)
                    removeSpell(_spellEntry->Effects[i].TriggerSpell, true); // and remove any spells that the talent teaches

            for (uint8 i = 0; i < _spellEntry->EffectCount; ++i)
                if (_spellEntry->Effects[i].ApplyAuraName == SPELL_AURA_OVERRIDE_ACTIONBAR_SPELLS || _spellEntry->Effects[i].ApplyAuraName == SPELL_AURA_OVERRIDE_ACTIONBAR_SPELLS_2)
                    RemoveAurasDueToSpell(_spellEntry->Effects[i].BasePoints);
        }

    }

    RemoveSpecializationSpells();

    // set glyphs
    for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
        // remove secondary glyph
        if (uint32 oldglyph = GetGlyph(GetActiveSpec(), slot))
            if (GlyphPropertiesEntry const* old_gp = sGlyphPropertiesStore.LookupEntry(oldglyph))
                RemoveAurasDueToSpell(old_gp->SpellId);

    float l_HPPct = GetHealthPct();

    for (uint8 l_I = 0; l_I < INVENTORY_SLOT_BAG_END; ++l_I)
    {
        if (Item* l_Item = m_items[l_I])
        {
            _ApplyItemMods(l_Item, l_I, false);
            RemoveItemsSetItem(this, l_Item->GetTemplate());
        }
    }

    SetActiveSpec(spec);
    SetUInt32Value(PLAYER_FIELD_CURRENT_SPEC_ID, GetSpecializationId(spec));

    for (uint8 l_I = 0; l_I < INVENTORY_SLOT_BAG_END; ++l_I)
    {
        if (Item* l_Item = m_items[l_I])
        {
            _ApplyItemMods(l_Item, l_I, true);
            AddItemsSetItem(this, l_Item);
        }
    }

    SetHealth(GetMaxHealth() * l_HPPct / 100.0f);

    uint32 usedTalentPoint = 0;
    for (auto itr : *GetTalentMap(GetActiveSpec()))
    {
        learnSpell(itr.first, false);
        usedTalentPoint++;
    }

    // set glyphs
    for (uint8 slot = 0; slot < MAX_GLYPH_SLOT_INDEX; ++slot)
    {
        uint32 glyph = GetGlyph(GetActiveSpec(), slot);

        // apply primary glyph
        if (glyph)
        {
            bool l_CanApplyGlyph = true;

            if (GlyphPropertiesEntry const* l_GlyphProperties = sGlyphPropertiesStore.LookupEntry(glyph))
            {
                if (l_GlyphProperties->GlyphExclusiveCategoryID)
                {
                    for (uint8 l_GlyphSlotIndex = 0; l_GlyphSlotIndex < MAX_GLYPH_SLOT_INDEX; ++l_GlyphSlotIndex)
                    {
                        uint32 l_GlyphID = GetGlyph(GetActiveSpec(), l_GlyphSlotIndex);
                        if (!l_GlyphID)
                            continue;

                        GlyphPropertiesEntry const* l_GlyphPropertiesCheck = sGlyphPropertiesStore.LookupEntry(l_GlyphID);
                        if (!l_GlyphPropertiesCheck)
                            continue;

                        if (l_GlyphPropertiesCheck->GlyphExclusiveCategoryID == l_GlyphProperties->GlyphExclusiveCategoryID && glyph != l_GlyphID)
                        {
                            l_CanApplyGlyph = false;
                            break;
                        }
                    }

                    if (!l_CanApplyGlyph)
                        continue;
                }

                CastSpell(this, l_GlyphProperties->SpellId, true);
            }
        }

        SetGlyph(slot, glyph);
    }

    for (uint8 i = POWER_MANA; i < MAX_POWERS; ++i)
    {
        SetMaxPower(Powers(i), GetCreatePowers(Powers(i)));
        SetPower(Powers(i), 0);
    }

    SetUsedTalentCount(usedTalentPoint);
    InitTalentForLevel();
    InitSpellForLevel();
    if (Powers l_PowerType = getPowerType())
        UpdateMaxPower(l_PowerType);

    {
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_ACTIONS_SPEC);
        stmt->setUInt32(0, GetGUIDLow());
        stmt->setUInt8(1, GetActiveSpec());
        if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
            _LoadActions(result);
    }

    SendActionButtons(1);
}

void Player::ResetTimeSync()
{
    m_timeSyncCounter = 0;
    m_timeSyncTimer = 0;
    m_timeSyncClient = 0;
    m_timeSyncServer = getMSTime();
}

void Player::SendTimeSync()
{
    WorldPacket data(SMSG_TIME_SYNC_REQUEST, 4);
    data << uint32(m_timeSyncCounter++);
    GetSession()->SendPacket(&data);

    // Schedule next sync in 10 sec
    m_timeSyncTimer = 10000;
    m_timeSyncServer = getMSTime();
}

void Player::SetReputation(uint32 factionentry, uint32 value)
{
    GetReputationMgr().SetReputation(sFactionStore.LookupEntry(factionentry), value);
}

uint32 Player::GetReputation(uint32 factionentry)
{
    return GetReputationMgr().GetReputation(sFactionStore.LookupEntry(factionentry));
}

std::string Player::GetGuildName()
{
    return GetGuildId() ? sGuildMgr->GetGuildById(GetGuildId())->GetName() : "";
}

void Player::MountSetFavorite(uint32 p_SpellID, bool p_IsFavorite)
{
    if (m_spells.find(p_SpellID) == m_spells.end())
        return;

    m_spells[p_SpellID]->IsMountFavorite = p_IsFavorite;
    m_spells[p_SpellID]->state = PLAYERSPELL_CHANGED;

    WorldPacket l_Data(SMSG_ACCOUNT_MOUNT_UPDATE, 1 + 4 + 4 + 4 + 1);
    l_Data.WriteBit(false); ///< Is full update
    l_Data.FlushBits();
    l_Data << uint32(1);    ///< One update
    l_Data << uint32(1);    ///< One update

    l_Data << uint32(p_SpellID);
    l_Data.WriteBit(p_IsFavorite);
    l_Data.FlushBits();

    SendDirectMessage(&l_Data);
}

void Player::SendDuelCountdown(uint32 p_Coutdown)
{
    WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
    data << uint32(p_Coutdown);                 ///< seconds
    GetSession()->SendPacket(&data);
}

void Player::AddRefundReference(uint32 p_Iter)
{
    m_refundableItems.insert(p_Iter);
}

void Player::DeleteRefundReference(uint32 p_Iter)
{
    std::set<uint32>::iterator l_Iter = m_refundableItems.find(p_Iter);
    if (l_Iter != m_refundableItems.end())
        m_refundableItems.erase(l_Iter);
}

void Player::SendRefundInfo(Item* p_Item)
{
    /// This function call unset ITEM_FLAGS_REFUNDABLE if played time is over 2 hours.
    p_Item->UpdatePlayedTime(this);

    if (!p_Item->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE))
        return;

    if (GetGUIDLow() != p_Item->GetRefundRecipient()) ///< Formerly refundable item got traded
    {
        p_Item->SetNotRefundable(this);
        return;
    }

    ItemExtendedCostEntry const* l_ExtendedCost = sItemExtendedCostStore.LookupEntry(p_Item->GetPaidExtendedCost());
    if (!l_ExtendedCost)
        return;

    ObjectGuid l_ItemGUID = p_Item->GetGUID();
    WorldPacket l_Data(SMSG_SET_ITEM_PURCHASE_DATA);

    l_Data.appendPackGUID(l_ItemGUID);

    /// Content
    {
        l_Data << uint32(p_Item->GetPaidMoney());                               ///< Money cost

        for (uint8 l_I = 0; l_I < MAX_ITEM_EXT_COST_ITEMS; ++l_I)
        {
            l_Data << uint32(l_ExtendedCost->RequiredItem[l_I]);
            l_Data << uint32(l_ExtendedCost->RequiredItemCount[l_I]);
        }

        for (uint8 l_I = 0; l_I < MAX_ITEM_EXT_COST_CURRENCIES; ++l_I)
        {
            l_Data << uint32(l_ExtendedCost->RequiredCurrency[l_I]);
            l_Data << uint32(l_ExtendedCost->RequiredCurrencyCount[l_I]);
        }
    }

    l_Data << uint32(0);                                                        ///< Flags
    l_Data << uint32(GetTotalPlayedTime() - p_Item->GetPlayedTime());           ///< Time Left

    GetSession()->SendPacket(&l_Data);
}

Item* Player::AddItem(uint32 p_ItemId, uint32 p_Count, std::list<uint32> p_Bonuses, bool p_FromShop)
{
    ItemPosCountVec l_Dest;
    InventoryResult l_Message = CanStoreNewItem(NULL_BAG, NULL_SLOT, l_Dest, p_ItemId, p_Count);

    if (l_Message != EQUIP_ERR_OK)
        return nullptr;

    Item* l_Item = StoreNewItem(l_Dest, p_ItemId, true, Item::GenerateItemRandomPropertyId(p_ItemId));
    if (l_Item)
    {
        for (auto l_Bonus : p_Bonuses)
            l_Item->AddItemBonus(l_Bonus);

        std::vector<uint32> l_Bonus;
        Item::GenerateItemBonus(l_Item->GetEntry(), ItemContext::None, l_Bonus);
        l_Item->AddItemBonuses(l_Bonus);

        if (p_FromShop)
            l_Item->SetCustomFlags(ItemCustomFlags::FromStore);

        SendNewItem(l_Item, p_Count, true, false);

        return l_Item;
    }

    return nullptr;
}

void Player::SendItemRefundResult(Item* p_Item, ItemExtendedCostEntry const* p_ExtendedCost, uint8 p_Error)
{
    WorldPacket l_Data(Opcodes::SMSG_ITEM_PURCHASE_REFUND_RESULT);
    l_Data.appendPackGUID(p_Item->GetGUID());
    l_Data << uint8(p_Error);
    l_Data.WriteBit(!p_Error);

    if (!p_Error)
    {
        l_Data << uint32(p_Item->GetPaidMoney());

        for (uint8 l_I = 0; l_I < MAX_ITEM_EXT_COST_ITEMS; ++l_I)
        {
            l_Data << uint32(p_ExtendedCost->RequiredItem[l_I]);<--- Possible null pointer dereference: p_ExtendedCost
            l_Data << uint32(p_ExtendedCost->RequiredItemCount[l_I]);<--- Possible null pointer dereference: p_ExtendedCost
        }

        for (uint8 l_I = 0; l_I < MAX_ITEM_EXT_COST_CURRENCIES; ++l_I)
        {
            CurrencyTypesEntry const* l_CurrTemplate = sCurrencyTypesStore.LookupEntry(p_ExtendedCost->RequiredCurrency[l_I]);<--- Possible null pointer dereference: p_ExtendedCost
            if (l_CurrTemplate != nullptr)
            {
                l_Data << uint32(p_ExtendedCost->RequiredCurrency[l_I]);<--- Possible null pointer dereference: p_ExtendedCost

                if (l_CurrTemplate->Flags & CurrencyFlags::CURRENCY_FLAG_HIGH_PRECISION)
                    l_Data << uint32(p_ExtendedCost->RequiredCurrencyCount[l_I]);<--- Possible null pointer dereference: p_ExtendedCost
                else
                    l_Data << uint32(p_ExtendedCost->RequiredCurrencyCount[l_I] / 100);<--- Possible null pointer dereference: p_ExtendedCost
            }
            else
            {
                l_Data << uint32(0);
                l_Data << uint32(0);
            }
        }
    }

    GetSession()->SendPacket(&l_Data);
}

void Player::RefundItem(Item* p_Item)
{
    if (!p_Item->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE))
        return;

    if (p_Item->IsRefundExpired())    ///< Item refund has expired
    {
        p_Item->SetNotRefundable(this);
        SendItemRefundResult(p_Item, NULL, 10);
        return;
    }

    if (GetGUIDLow() != p_Item->GetRefundRecipient()) ///< Formerly refundable item got traded
    {
        p_Item->SetNotRefundable(this);
        return;
    }

    ItemExtendedCostEntry const* l_ExtendedCost = sItemExtendedCostStore.LookupEntry(p_Item->GetPaidExtendedCost());
    if (!l_ExtendedCost)
        return;

    bool l_StoreError = false;
    for (uint8 l_I = 0; l_I < MAX_ITEM_EXT_COST_ITEMS; ++l_I)
    {
        uint32 l_Count = l_ExtendedCost->RequiredItemCount[l_I];
        uint32 l_ItemID = l_ExtendedCost->RequiredItem[l_I];

        if (l_Count && l_ItemID)
        {
            ItemPosCountVec l_Dest;
            InventoryResult l_InvResult = CanStoreNewItem(NULL_BAG, NULL_SLOT, l_Dest, l_ItemID, l_Count);
            if (l_InvResult != EQUIP_ERR_OK)
            {
                l_StoreError = true;
                break;
            }
         }
    }

    if (l_StoreError)
    {
        SendItemRefundResult(p_Item, l_ExtendedCost, 10);
        return;
    }

    /// Check total cap
    for (uint8 l_I = 0; l_I < MAX_ITEM_EXT_COST_CURRENCIES; ++l_I)
    {
        /// Second field in dbc is season count except one row
        if (l_I == 1 && l_ExtendedCost->ID != 2999)
            continue;

        uint32 l_CurrencyID = l_ExtendedCost->RequiredCurrency[l_I];
        CurrencyTypesEntry const* l_CurrencyType = sCurrencyTypesStore.LookupEntry(l_CurrencyID);
        if (!l_CurrencyType)
            continue;

        uint32 l_Count = l_ExtendedCost->RequiredCurrencyCount[l_I] / l_CurrencyType->GetPrecision();
        uint32 l_CurrCount = GetCurrency(l_CurrencyID, l_CurrencyType->HasPrecision());

        if (l_CurrencyType->TotalCap && (l_CurrCount + l_Count > (l_CurrencyType->TotalCap / l_CurrencyType->GetPrecision())))
        {
            SendItemRefundResult(p_Item, l_ExtendedCost, 10);
            return;
        }
    }

    SendItemRefundResult(p_Item, l_ExtendedCost, 0);

    uint32 l_MoneyRefund = p_Item->GetPaidMoney();  ///< Item-> will be invalidated in DestroyItem

    /// Save all relevant data to DB to prevent desynchronizing exploits
    SQLTransaction l_Transaction = CharacterDatabase.BeginTransaction();

    /// Delete any references to the refund data
    p_Item->SetNotRefundable(this, true, &l_Transaction);

    /// Destroy item
    DestroyItem(p_Item->GetBagSlot(), p_Item->GetSlot(), true);

    /// Grant back extended cost items ...
    for (uint8 l_I = 0; l_I < MAX_ITEM_EXT_COST_CURRENCIES; ++l_I)
    {
        uint32 l_Count = l_ExtendedCost->RequiredItemCount[l_I];
        uint32 l_ItemID = l_ExtendedCost->RequiredItem[l_I];

        if (l_Count && l_ItemID)
        {
            ItemPosCountVec l_Dest;
            InventoryResult l_InvResult = CanStoreNewItem(NULL_BAG, NULL_SLOT, l_Dest, l_ItemID, l_Count);
            ASSERT(l_InvResult == EQUIP_ERR_OK) ///< Already checked before
            Item* l_Item = StoreNewItem(l_Dest, l_ItemID, true);
            SendNewItem(l_Item, l_Count, true, false, true);
        }
    }

    /// ... and currencies
    for (uint8 l_I = 0; l_I < MAX_ITEM_EXT_COST_CURRENCIES; ++l_I)
    {
        /// Second field in dbc is season count except one row
        if (l_I == 1 && l_ExtendedCost->ID != 2999)
            continue;

        uint32 l_CurrencyID = l_ExtendedCost->RequiredCurrency[l_I];
        uint32 l_Count = l_ExtendedCost->RequiredCurrencyCount[l_I];

        if (l_CurrencyID && l_Count)
            ModifyCurrency(l_CurrencyID, l_Count, false, true, true);
    }

    /// Grant back money
    if (l_MoneyRefund)
        ModifyMoney(l_MoneyRefund); ///< Saved in SaveInventoryAndGoldToDB

    /// Grant back Arena and Honor points ?

    SaveInventoryAndGoldToDB(l_Transaction);

    CharacterDatabase.CommitTransaction(l_Transaction);
}

void Player::SetRandomWinner(bool isWinner)
{
    m_IsBGRandomWinner = isWinner;
    if (m_IsBGRandomWinner)
    {
        PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BATTLEGROUND_RANDOM);

        stmt->setUInt32(0, GetGUIDLow());

        CharacterDatabase.Execute(stmt);
    }
}

void Player::_LoadRandomBGStatus(PreparedQueryResult result)
{
    //QueryResult result = CharacterDatabase.PQuery("SELECT guid FROM character_battleground_random WHERE guid = '%u'", GetGUIDLow());

    if (result)
        m_IsBGRandomWinner = true;
}

uint32 Player::GetAverageItemLevelEquipped() const
{
    int32 l_Sum = 0;
    uint32 l_Count = 0;
    bool l_HasTwoHanded = false;

    for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        // don't check tabard, ranged, offhand or shirt
        if (i == EQUIPMENT_SLOT_TABARD || i == EQUIPMENT_SLOT_RANGED || i == EQUIPMENT_SLOT_BODY)
            continue;

        Item* l_Item = m_items[i];
        if (l_Item && l_Item->GetTemplate())
        {
            if (i == EQUIPMENT_SLOT_MAINHAND && l_Item->GetTemplate()->IsTwoHandedWeapon())
                l_HasTwoHanded = true;

            l_Sum += l_Item->GetTemplate()->GetItemLevelIncludingQuality(m_itemScale[i]);
            ++l_Count;
        }
        else if (i == EQUIPMENT_SLOT_OFFHAND && !CanTitanGrip() && (l_HasTwoHanded))
            continue;
        else
            ++l_Count;
    }

    if (!l_Count)
        return 0;

    return uint32(float(((float)l_Sum) / l_Count));
}

uint32 Player::GetAverageItemLevelTotal() const
{
    // If player has a 2h ignore offhand if not found (if found fury and count it)
    // If player does not have a 2h check offhand
    int l_EquipItemLevel[EQUIPMENT_SLOT_END];

    for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        // don't check tabard, ranged or shirt
        if (i == EQUIPMENT_SLOT_TABARD || i == EQUIPMENT_SLOT_RANGED || i == EQUIPMENT_SLOT_BODY)
        {
            l_EquipItemLevel[i] = 0;
            continue;
        }

        Item* l_Item = m_items[i];
        if (l_Item && l_Item->GetTemplate())
        {
            l_EquipItemLevel[i] = l_Item->GetTemplate()->GetItemLevelIncludingQuality(m_itemScale[i]);

            if (i == EQUIPMENT_SLOT_MAINHAND && ((CanDualWield() && l_Item->GetTemplate()->IsOneHanded()) || (CanTitanGrip() && l_Item->GetTemplate()->IsTwoHandedWeapon())))
                l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND] = std::max(l_EquipItemLevel[i], l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND]);

            if (i == EQUIPMENT_SLOT_OFFHAND && l_Item->GetTemplate()->Class == ITEM_CLASS_WEAPON)
                l_EquipItemLevel[EQUIPMENT_SLOT_MAINHAND] = std::max(l_EquipItemLevel[i], l_EquipItemLevel[EQUIPMENT_SLOT_MAINHAND]);

            continue;
        }

        l_EquipItemLevel[i] = 0;
    }

    l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET1] = std::max(l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET1], l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2]);
    l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2] = l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET1];
    l_EquipItemLevel[EQUIPMENT_SLOT_FINGER1] = std::max(l_EquipItemLevel[EQUIPMENT_SLOT_FINGER1], l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2]);
    l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2] = l_EquipItemLevel[EQUIPMENT_SLOT_FINGER1];

    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
    {
        if (Item* l_Item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
        {
            if (l_Item->IsSuitableForItemLevelCalulcation(true))
            {
                int slot = GetGuessedEquipSlot(l_Item->GetTemplate());
                int l_ThisIlvl = l_Item->GetTemplate()->GetItemLevelIncludingQuality(GetEquipItemLevelFor(l_Item->GetTemplate(), l_Item));

                if (slot != NULL_SLOT)
                {
                    if (slot == EQUIPMENT_SLOT_MAINHAND && ((CanDualWield() && l_Item->GetTemplate()->IsOneHanded()) || (CanTitanGrip() && l_Item->GetTemplate()->IsTwoHandedWeapon())))
                        l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND]);

                    if (slot == EQUIPMENT_SLOT_TRINKET1)
                        l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2]);

                    if (slot == EQUIPMENT_SLOT_FINGER1)
                        l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2]);

                    l_EquipItemLevel[slot] = std::max(l_EquipItemLevel[slot], l_ThisIlvl);
                }
            }
        }
    }

    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        if (Bag* pBag = GetBagByPos(i))
        {
            for (uint32 j = 0; j < pBag->GetBagSize(); j++)
            {
                if (Item* l_Item = pBag->GetItemByPos(j))
                {
                    if (l_Item->IsSuitableForItemLevelCalulcation(true))
                    {
                        int slot = GetGuessedEquipSlot(l_Item->GetTemplate());
                        int l_ThisIlvl = l_Item->GetTemplate()->GetItemLevelIncludingQuality(GetEquipItemLevelFor(l_Item->GetTemplate(), l_Item));

                        if (slot != NULL_SLOT)
                        {
                            if (slot == EQUIPMENT_SLOT_MAINHAND && ((CanDualWield() && l_Item->GetTemplate()->IsOneHanded()) || (CanTitanGrip() && l_Item->GetTemplate()->IsTwoHandedWeapon())))
                                l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND]);

                            if (slot == EQUIPMENT_SLOT_TRINKET1)
                                l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2]);

                            if (slot == EQUIPMENT_SLOT_FINGER1)
                                l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2]);

                            l_EquipItemLevel[slot] = std::max(l_EquipItemLevel[slot], l_ThisIlvl);
                        }
                    }
                }
            }
        }
    }

    int32 l_Sum = 0;
    uint32 l_Count = 0;
    bool l_HasTwoHanded = false;

    for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        // don't check tabard, ranged, offhand or shirt
        if (i == EQUIPMENT_SLOT_TABARD || i == EQUIPMENT_SLOT_RANGED || i == EQUIPMENT_SLOT_BODY)
            continue;

        Item* l_Item = m_items[i];
        if (l_Item && l_Item->GetTemplate())
        {
            if (i == EQUIPMENT_SLOT_MAINHAND && l_Item->GetTemplate()->IsTwoHandedWeapon())
                l_HasTwoHanded = true;

            l_Sum += l_EquipItemLevel[i];
            ++l_Count;
        }
        else if (i == EQUIPMENT_SLOT_OFFHAND && !CanTitanGrip() && (l_HasTwoHanded))
            continue;
        else
            ++l_Count;
    }

    if (!l_Count)
        return 0;

    return uint32(float(((float)l_Sum) / l_Count));
}


uint32 Player::GetAverageItemLevelTotalWithOrWithoutPvPBonus(bool p_PvP) const
{
    // If player has a 2h ignore offhand if not found (if found fury and count it)
    // If player does not have a 2h check offhand
    int l_EquipItemLevel[EQUIPMENT_SLOT_END];

    for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        // don't check tabard, ranged or shirt
        if (i == EQUIPMENT_SLOT_TABARD || i == EQUIPMENT_SLOT_RANGED || i == EQUIPMENT_SLOT_BODY)
        {
            l_EquipItemLevel[i] = 0;
            continue;
        }

        Item* l_Item = m_items[i];
        if (l_Item && l_Item->GetTemplate())
        {
            l_EquipItemLevel[i] = GetEquipItemLevelFor(l_Item->GetTemplate(), l_Item, !p_PvP, p_PvP);

            if (i == EQUIPMENT_SLOT_MAINHAND && ((CanDualWield() && l_Item->GetTemplate()->IsOneHanded()) || (CanTitanGrip() && l_Item->GetTemplate()->IsTwoHandedWeapon())))
                l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND] = std::max(l_EquipItemLevel[i], l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND]);

            if (i == EQUIPMENT_SLOT_OFFHAND && l_Item->GetTemplate()->Class == ITEM_CLASS_WEAPON)
                l_EquipItemLevel[EQUIPMENT_SLOT_MAINHAND] = std::max(l_EquipItemLevel[i], l_EquipItemLevel[EQUIPMENT_SLOT_MAINHAND]);

            continue;
        }

        l_EquipItemLevel[i] = 0;
    }

    l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET1] = std::max(l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET1], l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2]);
    l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2] = l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET1];
    l_EquipItemLevel[EQUIPMENT_SLOT_FINGER1] = std::max(l_EquipItemLevel[EQUIPMENT_SLOT_FINGER1], l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2]);
    l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2] = l_EquipItemLevel[EQUIPMENT_SLOT_FINGER1];

    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
    {
        if (Item* l_Item = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
        {
            if (l_Item->IsSuitableForItemLevelCalulcation(true))
            {
                int slot = GetGuessedEquipSlot(l_Item->GetTemplate());
                int l_ThisIlvl = l_Item->GetTemplate()->GetItemLevelIncludingQuality(GetEquipItemLevelFor(l_Item->GetTemplate(), l_Item));

                if (slot != NULL_SLOT)
                {
                    if (slot == EQUIPMENT_SLOT_MAINHAND && ((CanDualWield() && l_Item->GetTemplate()->IsOneHanded()) || (CanTitanGrip() && l_Item->GetTemplate()->IsTwoHandedWeapon())))
                        l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND]);

                    if (slot == EQUIPMENT_SLOT_TRINKET1)
                        l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2]);

                    if (slot == EQUIPMENT_SLOT_FINGER1)
                        l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2]);

                    l_EquipItemLevel[slot] = std::max(l_EquipItemLevel[slot], l_ThisIlvl);
                }
            }
        }
    }

    for (uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
    {
        if (Bag* pBag = GetBagByPos(i))
        {
            for (uint32 j = 0; j < pBag->GetBagSize(); j++)
            {
                if (Item* l_Item = pBag->GetItemByPos(j))
                {
                    if (l_Item->IsSuitableForItemLevelCalulcation(true))
                    {
                        int slot = GetGuessedEquipSlot(l_Item->GetTemplate());
                        int l_ThisIlvl = l_Item->GetTemplate()->GetItemLevelIncludingQuality(GetEquipItemLevelFor(l_Item->GetTemplate(), l_Item));

                        if (slot != NULL_SLOT)
                        {
                            if (slot == EQUIPMENT_SLOT_MAINHAND && ((CanDualWield() && l_Item->GetTemplate()->IsOneHanded()) || (CanTitanGrip() && l_Item->GetTemplate()->IsTwoHandedWeapon())))
                                l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_OFFHAND]);

                            if (slot == EQUIPMENT_SLOT_TRINKET1)
                                l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_TRINKET2]);

                            if (slot == EQUIPMENT_SLOT_FINGER1)
                                l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2] = std::max(l_ThisIlvl, l_EquipItemLevel[EQUIPMENT_SLOT_FINGER2]);

                            l_EquipItemLevel[slot] = std::max(l_EquipItemLevel[slot], l_ThisIlvl);
                        }
                    }
                }
            }
        }
    }

    uint32 l_Sum = 0;
    uint32 l_Count = 0;

    for (int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
    {
        if (i == EQUIPMENT_SLOT_TABARD || i == EQUIPMENT_SLOT_RANGED || i == EQUIPMENT_SLOT_BODY)
            continue;

        if (i == EQUIPMENT_SLOT_OFFHAND && !l_EquipItemLevel[i])
            continue;

        l_Sum += l_EquipItemLevel[i];
        ++l_Count;
    }

    if (!l_Count)
        return 0;

    return uint32(float(((float)l_Sum) / l_Count));
}

void Player::_LoadInstanceTimeRestrictions(PreparedQueryResult result)
{
    if (!result)
        return;

    do
    {
        Field* fields = result->Fetch();
        _instanceResetTimes.insert(InstanceTimeMap::value_type(fields[0].GetUInt32(), fields[1].GetUInt64()));
    }
    while (result->NextRow());
}

void Player::_LoadCUFProfiles(PreparedQueryResult result)
{
    if (result)
    {
        uint32 count = result->GetRowCount();
        if (count > MAX_CUF_PROFILES)
            count = MAX_CUF_PROFILES;

        m_cufProfiles.resize(count);

        uint32 i = 0;
        do
        {
            Field* fields = result->Fetch();

            CUFProfile& profile = m_cufProfiles[i];

            std::string name = fields[0].GetString();
            uint32 lenght = fields[0].GetStringLength();
            if (lenght > MAX_CUF_PROFILE_NAME_LENGTH)
                continue;

            profile.Name = name;
            profile.l_NameLen = lenght;

            UnpackDBBinary(&profile.data, sizeof(profile.data), fields[1].GetCString(), fields[1].GetStringLength());

            ++i;
        }
        while (i < count && result->NextRow());
    }
    else
        m_cufProfiles.clear();
}

void Player::SendCUFProfiles()
{
    WorldPacket l_Data(SMSG_LOAD_CUF_PROFILES);

    l_Data << uint32(m_cufProfiles.size());

    for (uint32 i = 0; i < m_cufProfiles.size(); ++i)
    {
        CUFProfile& l_Profile = m_cufProfiles[i];
        CUFProfileData& l_ProfileData = l_Profile.data;

        l_Data.WriteBits(l_Profile.l_NameLen, 7);
        l_Data.WriteBit(l_ProfileData.KeepGroupsTogether);
        l_Data.WriteBit(l_ProfileData.DisplayPets);
        l_Data.WriteBit(l_ProfileData.DisplayMainTankAndAssist);
        l_Data.WriteBit(l_ProfileData.DisplayHealPrediction);
        l_Data.WriteBit(l_ProfileData.DisplayAggroHighlight);
        l_Data.WriteBit(l_ProfileData.DisplayOnlyDispellableDebuffs);
        l_Data.WriteBit(l_ProfileData.DisplayPowerBar);
        l_Data.WriteBit(l_ProfileData.DisplayBorder);
        l_Data.WriteBit(l_ProfileData.UseClassColors);
        l_Data.WriteBit(l_ProfileData.HorizontalGroups);
        l_Data.WriteBit(l_ProfileData.DisplayNonBossDebuffs);
        l_Data.WriteBit(l_ProfileData.DynamicPosition);
        l_Data.WriteBit(l_ProfileData.Locked);
        l_Data.WriteBit(l_ProfileData.Shown);
        l_Data.WriteBit(l_ProfileData.AutoActivate2Players);
        l_Data.WriteBit(l_ProfileData.AutoActivate3Players);
        l_Data.WriteBit(l_ProfileData.AutoActivate5Players);
        l_Data.WriteBit(l_ProfileData.AutoActivate10Players);
        l_Data.WriteBit(l_ProfileData.AutoActivate15Players);
        l_Data.WriteBit(l_ProfileData.AutoActivate25Players);
        l_Data.WriteBit(l_ProfileData.AutoActivate40Players);
        l_Data.WriteBit(l_ProfileData.AutoActivateSpec1);
        l_Data.WriteBit(l_ProfileData.AutoActivateSpec2);
        l_Data.WriteBit(l_ProfileData.AutoActivatePvP);
        l_Data.WriteBit(l_ProfileData.AutoActivatePvE);
        l_Data.FlushBits();

        l_Data << uint16(l_ProfileData.FrameHeight);
        l_Data << uint16(l_ProfileData.FrameWidth);
        l_Data << uint8(l_ProfileData.SortBy);
        l_Data << uint8(l_ProfileData.HealthText);
        l_Data << uint8(l_ProfileData.TopPoint);
        l_Data << uint8(l_ProfileData.BottomPoint);
        l_Data << uint8(l_ProfileData.LeftPoint);
        l_Data << uint16(l_ProfileData.TopOffset);
        l_Data << uint16(l_ProfileData.BottomOffset);
        l_Data << uint16(l_ProfileData.LeftOffset);

        l_Data.append(l_Profile.Name.c_str(), l_Profile.l_NameLen);
    }

    GetSession()->SendPacket(&l_Data);
}

void Player::_SaveInstanceTimeRestrictions(SQLTransaction& trans)
{
    if (_instanceResetTimes.empty())
        return;

    PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ACCOUNT_INSTANCE_LOCK_TIMES);
    stmt->setUInt32(0, GetSession()->GetAccountId());
    trans->Append(stmt);

    for (InstanceTimeMap::const_iterator itr = _instanceResetTimes.begin(); itr != _instanceResetTimes.end(); ++itr)
    {
        stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ACCOUNT_INSTANCE_LOCK_TIMES);
        stmt->setUInt32(0, GetSession()->GetAccountId());
        stmt->setUInt32(1, itr->first);
        stmt->setUInt64(2, itr->second);
        trans->Append(stmt);
    }
}

bool Player::IsInWhisperWhiteList(uint64 guid)
{
    for (WhisperListContainer::const_iterator itr = WhisperList.begin(); itr != WhisperList.end(); ++itr)
    {
        if (*itr == guid)
            return true;
    }
    return false;
}

bool Player::CanSwitch() const
{
    if (getRace() != RACE_WORGEN)
        return false;

    if (isInCombat() || !HasAuraType(SPELL_AURA_ALLOW_WORGEN_TRANSFORM))
        return false;

    return true;
}

void Player::SwitchForm()<--- The function 'SwitchForm' is never used.
{
    if (!CanSwitch())
        return;

    if (IsInWorgenForm())
        SwitchToHumanForm();
    else
        SwitchToWorgenForm();
}

void Player::SendPetTameResult(PetTameResult p_Result)
{
    WorldPacket l_Data(SMSG_PET_TAME_FAILURE, 4);
    l_Data << uint8(p_Result);

    GetSession()->SendPacket(&l_Data);
}

uint8 Player::GetNextVoidStorageFreeSlot() const
{
    for (uint8 i = 0; i < VOID_STORAGE_MAX_SLOT; ++i)
        if (!_voidStorageItems[i]) // unused item
            return i;

    return VOID_STORAGE_MAX_SLOT;
}

uint8 Player::GetNumOfVoidStorageFreeSlots() const
{
    uint8 count = 0;

    for (uint8 i = 0; i < VOID_STORAGE_MAX_SLOT; ++i)
        if (!_voidStorageItems[i])
            count++;

    return count;
}

uint8 Player::AddVoidStorageItem(const VoidStorageItem& item)
{
    uint8 slot = GetNextVoidStorageFreeSlot();

    if (slot >= VOID_STORAGE_MAX_SLOT)
    {
        GetSession()->SendVoidStorageTransferResult(VOID_TRANSFER_ERROR_FULL);
        return 255;
    }

    _voidStorageItems[slot] = new VoidStorageItem(item.ItemId, item.ItemEntry,
        item.CreatorGuid, item.ItemRandomPropertyId, item.ItemSuffixFactor, item.Bonuses);
    return slot;
}

void Player::AddVoidStorageItemAtSlot(uint8 slot, const VoidStorageItem& item)<--- The function 'AddVoidStorageItemAtSlot' is never used.
{
    if (slot >= VOID_STORAGE_MAX_SLOT)
    {
        GetSession()->SendVoidStorageTransferResult(VOID_TRANSFER_ERROR_FULL);
        return;
    }

    if (_voidStorageItems[slot])
    {
        sLog->outError(LOG_FILTER_GENERAL, "Player::AddVoidStorageItemAtSlot - Player (GUID: %u, name: %s) tried to add an item to an used slot (item id: " UI64FMTD ", entry: %u, slot: %u).", GetGUIDLow(), GetName(), _voidStorageItems[slot]->ItemId, _voidStorageItems[slot]->ItemEntry, slot);
        GetSession()->SendVoidStorageTransferResult(VOID_TRANSFER_ERROR_INTERNAL_ERROR_1);
        return;
    }

    _voidStorageItems[slot] = new VoidStorageItem(item.ItemId, item.ItemId,
        item.CreatorGuid, item.ItemRandomPropertyId, item.ItemSuffixFactor, item.Bonuses);
}

void Player::DeleteVoidStorageItem(uint8 slot)
{
    if (slot >= VOID_STORAGE_MAX_SLOT)
    {
        GetSession()->SendVoidStorageTransferResult(VOID_TRANSFER_ERROR_INTERNAL_ERROR_1);
        return;
    }

    delete _voidStorageItems[slot];
    _voidStorageItems[slot] = NULL;
}

bool Player::SwapVoidStorageItem(uint8 oldSlot, uint8 newSlot)
{
    if (oldSlot >= VOID_STORAGE_MAX_SLOT || newSlot >= VOID_STORAGE_MAX_SLOT || oldSlot == newSlot)
        return false;

    std::swap(_voidStorageItems[newSlot], _voidStorageItems[oldSlot]);
    return true;
}

VoidStorageItem* Player::GetVoidStorageItem(uint8 slot) const
{
    if (slot >= VOID_STORAGE_MAX_SLOT)
    {
        GetSession()->SendVoidStorageTransferResult(VOID_TRANSFER_ERROR_INTERNAL_ERROR_1);
        return NULL;
    }

    return _voidStorageItems[slot];
}

VoidStorageItem* Player::GetVoidStorageItem(uint64 id, uint8& slot) const
{
    for (uint8 i = 0; i < VOID_STORAGE_MAX_SLOT; ++i)
    {
        if (_voidStorageItems[i] && _voidStorageItems[i]->ItemId == id)
        {
            slot = i;
            return _voidStorageItems[i];
        }
    }

    return NULL;
}

void Player::SendMovementSetCanTransitionBetweenSwimAndFly(bool p_Apply)
{
    WorldPacket l_Data;

    if (p_Apply)
    {
        l_Data.Initialize(SMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY, 2 + 16 + 4);
        l_Data.appendPackGUID(GetGUID());
        l_Data << uint32(0);                ///< Movement counter
    }
    else
    {
        l_Data.Initialize(SMSG_MOVE_UNSET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY, 2 + 16 + 4);
        l_Data.appendPackGUID(GetGUID());
        l_Data << uint32(0);                ///< Movement counter
    }

    SendDirectMessage(&l_Data);
}

/// Disable for now, we didn't use good value for scale / height
void Player::SendMovementSetCollisionHeight(float p_Height)
{
    CreatureDisplayInfoEntry const* l_MountDisplayInfo = sCreatureDisplayInfoStore.LookupEntry(GetUInt32Value(UNIT_FIELD_MOUNT_DISPLAY_ID));
    if (!l_MountDisplayInfo)
    {
        WorldPacket l_Data(SMSG_MOVE_SET_COLLISION_HEIGHT, 16 + 2 + 4 + 4 + 4 + 4 + 1);
        l_Data.appendPackGUID(GetGUID());                   ///< MoverGUID
        l_Data << uint32(sWorld->GetGameTime());            ///< SequenceIndex
        l_Data << float(p_Height);                          ///< Height
        l_Data << float(GetFloatValue(OBJECT_FIELD_SCALE)); ///< Scale
        l_Data << uint32(0);                                ///< MountDisplayID
        l_Data.WriteBits(UPDATE_COLLISION_HEIGHT_MOUNT, 2); ///< Reason
        SendDirectMessage(&l_Data);
        return;
    }

    WorldPacket l_Data(SMSG_MOVE_SET_COLLISION_HEIGHT, 16 + 2 + 4 + 4 + 4 + 4 + 1);
    l_Data.appendPackGUID(GetGUID());
    l_Data << uint32(sWorld->GetGameTime());
    l_Data << float(p_Height);
    l_Data << float(GetFloatValue(OBJECT_FIELD_SCALE));
    l_Data << uint32(l_MountDisplayInfo->Displayid);
    l_Data.WriteBits(UPDATE_COLLISION_HEIGHT_MOUNT, 2);
    SendDirectMessage(&l_Data);
}

float Player::GetCollisionHeight(bool p_Mounted)
{
    if (p_Mounted)
    {
        CreatureDisplayInfoEntry const* l_MountDisplayInfos = sCreatureDisplayInfoStore.LookupEntry(GetUInt32Value(EUnitFields::UNIT_FIELD_MOUNT_DISPLAY_ID));
        if (!l_MountDisplayInfos)
            return GetCollisionHeight(false);

        CreatureModelDataEntry const* l_CreatureModelData = sCreatureModelDataStore.LookupEntry(l_MountDisplayInfos->ModelId);
        if (!l_CreatureModelData)
            return GetCollisionHeight(false);

        CreatureDisplayInfoEntry const* l_DisplayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId());
        ASSERT (l_DisplayInfo);

        CreatureModelDataEntry const* l_ModelData = sCreatureModelDataStore.LookupEntry(l_DisplayInfo->ModelId);
        ASSERT (l_ModelData);

        float l_ScaleMod = GetFloatValue(EObjectFields::OBJECT_FIELD_SCALE); ///< 99% sure about this

        return l_ScaleMod * l_CreatureModelData->MountHeight + l_ModelData->CollisionHeight * 0.5f;
    }
    else
    {
        /// Dismounting case - use basic default model data
        CreatureDisplayInfoEntry const* l_DisplayInfo = sCreatureDisplayInfoStore.LookupEntry(GetNativeDisplayId());
        ASSERT (l_DisplayInfo);

        CreatureModelDataEntry const* l_ModelData = sCreatureModelDataStore.LookupEntry(l_DisplayInfo->ModelId);
        ASSERT (l_ModelData);

        return l_ModelData->CollisionHeight;
    }
}

void Player::SetMover(Unit* target)
{
    m_mover->m_movedPlayer = NULL;
    m_mover = target;
    m_mover->m_movedPlayer = this;

    if (m_mover)
    {
        WorldPacket data(SMSG_MOVE_SET_ACTIVE_MOVER);
        data.appendPackGUID(target->GetGUID());

        GetSession()->SendPacket(&data);
    }
}

void Player::ShowNeutralPlayerFactionSelectUI()
{
    WorldPacket data(SMSG_SHOW_NEUTRAL_PLAYER_FACTION_SELECT_UI);
    GetSession()->SendPacket(&data);
}

void Player::SetPersonnalXpRate(float p_PersonnalXPRate)
{
    m_PersonnalXpRate = p_PersonnalXPRate;

    PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_UPD_XP_RATE);
    l_Statement->setFloat(0, p_PersonnalXPRate);
    l_Statement->setUInt32(1, GetGUIDLow());
    CharacterDatabase.Execute(l_Statement);
}

void Player::HandleStoreGoldCallback(PreparedQueryResult result)
{
    // Load des golds
    if (result)
    {
        uint64 goldCount = 0;
        do
        {
            Field* fieldGold    = result->Fetch();
            uint64 gold         = uint64(fieldGold[0].GetUInt32()) * GOLD;
            uint32 transaction  = fieldGold[1].GetUInt32();

            if ((GetMoney() + gold) > MAX_MONEY_AMOUNT)
            {
                GetSession()->SendNotification(LANG_GOLD_ERROR1);
                GetSession()->SendNotification(LANG_GOLD_ERROR2);
                break;
            }

            goldCount+= gold;
            ModifyMoney(gold);

            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_BOUTIQUE_GOLD);
            stmt->setInt32(0, transaction);
            CharacterDatabase.Execute(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BOUTIQUE_GOLD_LOG);
            stmt->setInt32(0, transaction);
            stmt->setInt32(1, GetGUIDLow());
            stmt->setInt64(2, gold);
            CharacterDatabase.Execute(stmt);
        }
        while(result->NextRow());

        if (goldCount)
            GetSession()->SendNotification(LANG_GOLD_CONFIRM, (goldCount/GOLD));
    }
}

void Player::HandleStoreTitleCallback(PreparedQueryResult p_Result)
{
    // Load titles
    if (p_Result)
    {
        do
        {
            Field* l_TitleField = p_Result->Fetch();
            uint32 l_Title = l_TitleField[0].GetUInt32();
            uint32 l_Transaction = l_TitleField[1].GetUInt32();

            PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_BOUTIQUE_TITLE);
            stmt->setInt32(0, l_Transaction);
            CharacterDatabase.Execute(stmt);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_BOUTIQUE_TITLE_LOG);
            stmt->setInt32(0, l_Transaction);
            stmt->setInt32(1, GetGUIDLow());
            stmt->setInt32(2, l_Title);
            CharacterDatabase.Execute(stmt);

            CharTitlesEntry const* l_TitleInfo = sCharTitlesStore.LookupEntry(l_Title);
            if (!l_TitleInfo)
                continue;

            SetTitle(l_TitleInfo);
        }
        while (p_Result->NextRow());
    }
}

void Player::HandleStoreItemCallback(PreparedQueryResult result) ///< result is unused
{
}

void Player::HandleStoreLevelCallback(PreparedQueryResult result)
{
    PreparedStatement* stmt;

    // Load powerlevels
    if (result)
    {
        Field* fields = result->Fetch();
        uint32 level = fields[0].GetUInt32();

        if (level < getLevel() || level > DEFAULT_MAX_LEVEL)
        {
            GetSession()->SendNotification("Tentative de powerlevel vers un niveau inferieur ou vers un niveau plus eleve que le niveau maximum, veuillez contactez le support boutique si ce message apparait.");  // translate me
        }
        else
        {
            GiveLevel(level);

            stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_BOUTIQUE_LEVEL);
            stmt->setInt32(0, GetGUIDLow());
            CharacterDatabase.Execute(stmt);
        }
    }
}

namespace ProfessionBookSpells
{
    enum
    {
        Alchemy        = 156614,
        Blacksmithing  = 169923,
        Enchanting     = 161788,
        Engineering    = 161787,
        Inscription    = 161789,
        JewelCrafting  = 169926,
        LeatherWorking = 169925,
        Tailoring      = 169924,
        FirstAid       = 160329,
        Cooking        = 160360,
        Herbalism      = 158745,
        Mining         = 158754,
        Skinning       = 158756,
        Archaeology    = 158762,
        Fishing        = 160326
    };
}

namespace ProfessionAdditionalSpells
{
    enum
    {
        Prospecting = 31252,
    };
}

void Player::HandleStoreProfessionCallback(PreparedQueryResult p_Result)
{
    if (!p_Result)
        return;

    std::map<uint32, uint32> l_SkillLearningSpells = 
    {
        { SkillType::SKILL_ALCHEMY,        ProfessionBookSpells::Alchemy        },
        { SkillType::SKILL_BLACKSMITHING,  ProfessionBookSpells::Blacksmithing  },
        { SkillType::SKILL_ENCHANTING,     ProfessionBookSpells::Enchanting     },
        { SkillType::SKILL_ENGINEERING,    ProfessionBookSpells::Engineering    },
        { SkillType::SKILL_INSCRIPTION,    ProfessionBookSpells::Inscription    },
        { SkillType::SKILL_JEWELCRAFTING,  ProfessionBookSpells::JewelCrafting  },
        { SkillType::SKILL_LEATHERWORKING, ProfessionBookSpells::LeatherWorking },
        { SkillType::SKILL_TAILORING,      ProfessionBookSpells::Tailoring      },
        { SkillType::SKILL_FIRST_AID,      ProfessionBookSpells::FirstAid       },
        { SkillType::SKILL_COOKING,        ProfessionBookSpells::Cooking        },
        { SkillType::SKILL_HERBALISM,      ProfessionBookSpells::Herbalism      },
        { SkillType::SKILL_MINING,         ProfessionBookSpells::Mining         },
        { SkillType::SKILL_SKINNING,       ProfessionBookSpells::Skinning       },
        { SkillType::SKILL_ARCHAEOLOGY,    ProfessionBookSpells::Archaeology    },
        { SkillType::SKILL_FISHING,        ProfessionBookSpells::Fishing        }
    };

    do 
    {
        Field* l_Fields     = p_Result->Fetch();
        uint32 l_SkillID    = l_Fields[0].GetUInt32();
        bool   l_Recipe     = l_Fields[1].GetBool();

        auto it = l_SkillLearningSpells.find(l_SkillID);
        if (it == l_SkillLearningSpells.end())
            continue;

        uint32 l_SpellID = it->second;

        if (getLevel() < 90)
            continue;
        
        if (IsPrimaryProfessionSkill(l_SkillID) && !HasSkill(l_SkillID) && GetFreePrimaryProfessionPoints() == 0)
            continue;

        /// Learn the skill to dreanor rank
        CastSpell(this, l_SpellID, true);

        /// Up skill to 700
        SetSkill(l_SkillID, GetSkillStep(l_SkillID), 700, 700);

        if (l_Recipe)
        {
            const std::list<SkillLineAbilityEntry const*>& l_Abilities = sSpellMgr->GetTradeSpellFromSkill(l_SkillID);
            for (auto l_Abilitie : l_Abilities)
            {
                if (l_Abilitie->spellId > 155748)   ///< last 5.4.7 spellid
                    continue;

                learnSpell(l_Abilitie->spellId, false);
            }
        }

        if (l_SkillID == SkillType::SKILL_JEWELCRAFTING)
            learnSpell(ProfessionAdditionalSpells::Prospecting, false);             ///< Prospecting

        /// We also need to learn it for herbalism
        if (l_SkillID == SkillType::SKILL_HERBALISM)
            learnSpell(l_SpellID, false);

        PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_DEL_STORE_PROFESSION);
        l_Statement->setUInt32(0, GetGUIDLow());
        l_Statement->setUInt32(1, l_SkillID);
        CharacterDatabase.Execute(l_Statement);
    }
    while (p_Result->NextRow());
}

void Player::CheckSpellAreaOnQuestStatusChange(uint32 quest_id)
{
    uint32 zone = 0, area = 0;

    SpellAreaForQuestMapBounds saBounds = sSpellMgr->GetSpellAreaForQuestMapBounds(quest_id);
    if (saBounds.first != saBounds.second)
    {
        GetZoneAndAreaId(zone, area);

        for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
        {
            if (zone != itr->second->areaId && area != itr->second->areaId)
                continue;

            if (itr->second->IsFitToRequirements(this, zone, area))
            {
                if (itr->second->autocast)
                    if (!HasAura(itr->second->spellId))
                        CastSpell(this, itr->second->spellId, true);
            }
            else
                RemoveAurasDueToSpell(itr->second->spellId);
        }
    }

    saBounds = sSpellMgr->GetSpellAreaForQuestEndMapBounds(quest_id);
    if (saBounds.first != saBounds.second)
    {
        if (!zone || !area)
            GetZoneAndAreaId(zone, area);

        for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
        {
            if (zone != itr->second->areaId && area != itr->second->areaId)
                continue;

            if (itr->second->IsFitToRequirements(this, zone, area))
            {
                if (itr->second->autocast)
                    if (!HasAura(itr->second->spellId))
                        CastSpell(this, itr->second->spellId, true);
            }
            else
                RemoveAurasDueToSpell(itr->second->spellId);
        }
    }
}

void Player::CastPassiveTalentSpell(uint32 spellId)
{
    switch (spellId)
    {
        case 16188: // Ancestral Swiftness
            if (!HasAura(51470))
                CastSpell(this, 121617, true); ///< +5% melee/spell haste since 6.0.1 (Tue Oct 14 2014) Build 18537 
            break;
        case 96268: // Death's Advance
            if (!HasAura(124285))
                CastSpell(this, 124285, true); // +10% speed
            break;
        case 108415:// Soul Link
            RemoveAura(108503); // Remove Grimoire of sacrifice
            break;
        case 108499:// Grimoire of Supremacy
            if (!HasAura(108499))
                AddAura(108499, this);
            if (HasAura(152107)) ///< Demonic Servitude
                learnSpell(157901, false);  ///< WARLOCK_GRIMOIRE_INFERNAL
            break;
        case 108501:// Grimoire of Service
            learnSpell(111859, false);  ///< WARLOCK_GRIMOIRE_IMP
            learnSpell(111895, false);  ///< WARLOCK_GRIMOIRE_VOIDWALKER
            learnSpell(111896, false);  ///< WARLOCK_GRIMOIRE_SUCCUBUS
            learnSpell(111897, false);  ///< WARLOCK_GRIMOIRE_FELHUNTER

            if (GetSpecializationId() == SPEC_WARLOCK_DEMONOLOGY)
            {
                learnSpell(111898, false);  ///< WARLOCK_GRIMOIRE_FELGUARD
                if (HasAura(152107)) ///< Demonic Servitude
                {
                    learnSpell(157900, false);  ///< WARLOCK_GRIMOIRE_DOOMGUARD
                    learnSpell(157899, false);  ///< WARLOCK_GRIMOIRE_ABYSSAL
                }
            }
            break;
        default:
            break;
    }
}

void Player::RemovePassiveTalentSpell(SpellInfo const* info)
{
    if (!info)
        return;

    switch (info->Id)
    {
        case 46584: // Raise dead
            if (Pet* l_Pet = this->GetPet())
            {
                if (l_Pet->GetEntry() == 26125)
                    l_Pet->UnSummon();
            }
            break;
        case 16188: // Ancestral Swiftness
            RemoveAura(121617);
            break;
        case 108415:// Soul Link
            RemoveAura(108446);
            RemoveAura(108503); // Remove Grimoire of sacrifice
            break;
        case 108499:// Grimoire of Supremacy
            RemoveAura(108499);
            if (HasSpell(157899))
                removeSpell(157899, false, false);  // WARLOCK_GRIMOIRE_ABYSSAL
            break;
        case 108501:// Grimoire of Service
            if (HasSpell(111859))
                removeSpell(111859, false, false);  // WARLOCK_GRIMOIRE_IMP
            if (HasSpell(111895))
                removeSpell(111895, false, false);  // WARLOCK_GRIMOIRE_VOIDWALKER
            if (HasSpell(111896))
                removeSpell(111896, false, false);  // WARLOCK_GRIMOIRE_SUCCUBUS
            if (HasSpell(111897))
                removeSpell(111897, false, false);  // WARLOCK_GRIMOIRE_FELHUNTER
            if (HasSpell(111898))
                removeSpell(111898, false, false);  // WARLOCK_GRIMOIRE_FELGUARD
            if (HasSpell(157900))
                removeSpell(157900, false, false);  // WARLOCK_GRIMOIRE_DOOMGUARD
            if (HasSpell(157901))
                removeSpell(157901, false, false);  // WARLOCK_GRIMOIRE_INFERNAL
            break;
        default:
            break;
    }
}

Guild* Player::GetGuild()
{
    uint32 guildId = GetGuildId();
    return guildId ? sGuildMgr->GetGuildById(guildId) : 0;
}

void Player::FinishWeek()
{
    for (int slot = 0; slot < MAX_ARENA_SLOT; ++slot)
    {
        m_BestRatingOfWeek[slot] = 0;
        m_PrevWeekWins[slot] = m_WeekWins[slot];
        m_PrevWeekGames[slot] = m_WeekGames[slot];
        m_WeekGames[slot] = 0;
        m_WeekWins[slot] = 0;
    }
}

void Player::SetEmoteState(uint32 anim_id)
{
    HandleEmoteCommand(anim_id);
    m_emote = anim_id;
}

void Player::SendApplyMovementForce(uint64 p_Source, bool p_Apply, Position p_Direction, float p_Magnitude /*= 0.0f*/, uint8 p_Type /*= 0*/, G3D::Vector3 p_TransportPos /*= G3D::Vector3(0.0f, 0.0f, 0.0f)*/)
{
    if (p_Apply)
    {
        uint32 l_TransportID = GetTransport() ? GetTransport()->GetEntry() : 0;

        WorldPacket l_Data(SMSG_APPLY_MOVEMENT_FORCE, 2 + 16 + 4 + 2 + 16 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 4 + 1);
        l_Data.appendPackGUID(GetGUID());               ///< Mover GUID
        l_Data << uint32(0);                            ///< Sequence Index

        l_Data.appendPackGUID(p_Source);                ///< Movement ForceID
        l_Data << float(p_Direction.GetPositionX());    ///< Direction X
        l_Data << float(p_Direction.GetPositionY());    ///< Direction Y
        l_Data << float(p_Direction.GetPositionZ());    ///< Direction Z
        l_Data.WriteVector3(p_TransportPos);            ///< TransportPosition
        l_Data << uint32(l_TransportID);                ///< Transport ID
        l_Data << float(p_Magnitude);                   ///< Magnitude

        l_Data.WriteBits(p_Type, 2);                    ///< Force type, still one yet
        l_Data.FlushBits();

        SendMessageToSet(&l_Data, true);

        m_ActiveMovementForces.insert(p_Source);
    }
    else
    {
        WorldPacket l_Data(SMSG_UNAPPLY_MOVEMENT_FORCE, (2 * (2 + 16)) + 4);
        l_Data.appendPackGUID(GetGUID()); ///< Mover GUID
        l_Data << uint32(0);              ///< Sequence Index
        l_Data.appendPackGUID(p_Source);  ///< Movement ForceID

        SendMessageToSet(&l_Data, true);

        m_ActiveMovementForces.erase(p_Source);
    }
}

void Player::RemoveAllMovementForces(uint32 p_Entry /*=0*/)
{
    std::set<uint64> l_ActiveMovementForces;

    if (!p_Entry)
        l_ActiveMovementForces = m_ActiveMovementForces;
    else
    {
        for (std::set<uint64>::iterator l_Itr = m_ActiveMovementForces.begin(); l_Itr != m_ActiveMovementForces.end(); ++l_Itr)
        {
            if (WorldObject* l_Obj = ObjectAccessor::GetWorldObject(*this, *l_Itr))
            {
                if (l_Obj->GetEntry() == p_Entry)
                    l_ActiveMovementForces.insert(l_Obj->GetGUID());
            }
        }
    }

    for (uint64 l_ForceID : l_ActiveMovementForces)
        SendApplyMovementForce(l_ForceID, false, Position());
}

bool Player::HasMovementForce(uint64 p_Source /*= 0*/, bool p_IsEntry /*=false*/)
{
/* Removed because some Unit* can also be source of movement force
    if (sAreaTriggerStore.LookupEntry(GUID_ENPART(p_Source)) || GUID_HIPART(p_Source) != HIGHGUID_AREATRIGGER)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Invalid source for movement force. (GUID: 0x" UI64FMTD " AreaTrigger entry not found in DBC)", p_Source);
        return false;
    }
*/
    /// No Guid? Just returns if player has at least one movement force applied
    if (!p_Source)
        return !m_ActiveMovementForces.empty();

    /// Entry?
    if (p_IsEntry)
    {
        if (uint32(p_Source) == p_Source)
        {
            for (std::set<uint64>::iterator l_Itr = m_ActiveMovementForces.begin(); l_Itr != m_ActiveMovementForces.end(); ++l_Itr)
            {
                if (WorldObject* l_Object = ObjectAccessor::GetWorldObject(*this, *l_Itr))
                {
                    if (l_Object->GetEntry() == p_Source)
                        return true;
                }
            }

            return false;
        }
        /// Not a valid entry
        return false;
    }

    /// Guid?
    return m_ActiveMovementForces.find(p_Source) != m_ActiveMovementForces.end();
}

void Player::SendResumeToken(uint32 token)
{
    WorldPacket data(SMSG_RESUME_TOKEN, 5);
    data << uint32(token);
    data.WriteBit(token == m_tokenCounter);
    data.FlushBits();
    GetSession()->SendPacket(&data);
}

void Player::SendRefreshSpellMods()
{
    flag128 l_Mask = 0;
    uint32 l_PctModifierTypeCount;
    uint32 l_FlatModifierTypeCount;
    uint32 l_PctModifiersCount = 0;
    uint32 l_FlatModifiersCount = 0;
    uint32 l_MaskIndex;
    ByteBuffer l_PctBuffer;
    ByteBuffer l_FlatBuffer;
    int i = 0; ///< i is unused<--- Variable 'i' is assigned a value that is never used.

    for (int l_SpellModOp = 0; l_SpellModOp < MAX_SPELLMOD; ++l_SpellModOp)
    {
        if (!m_spellMods[l_SpellModOp].size())
            continue;

        l_PctModifierTypeCount = 0;
        l_FlatModifierTypeCount = 0;
        l_MaskIndex = 0;

        ByteBuffer l_SubFlatBuffer(1024);
        ByteBuffer l_SubPctBuffer(1024);

        for (int l_EffectIndex = 0; l_EffectIndex < 128; ++l_EffectIndex)
        {
            if (l_EffectIndex != 0 && (l_EffectIndex % 32) == 0)
                l_Mask[l_MaskIndex++] = 0;

            l_Mask[l_MaskIndex] = uint32(1) << (l_EffectIndex - (32 * l_MaskIndex));

            float l_PctValue = 1.0f;
            for (SpellModList::iterator l_It = m_spellMods[l_SpellModOp].begin(); l_It != m_spellMods[l_SpellModOp].end(); ++l_It)
                if ((*l_It)->type == SPELLMOD_PCT && (*l_It)->mask & l_Mask)
                    l_PctValue += float((*l_It)->value) / 100.0f;

            if (l_PctValue != 1.0f)
            {
                l_SubPctBuffer << float(l_PctValue);
                l_SubPctBuffer << uint8(l_EffectIndex);

                ++l_PctModifierTypeCount;
            }

            float l_FlatValue = 0.0f;
            for (SpellModList::iterator itr = m_spellMods[l_SpellModOp].begin(); itr != m_spellMods[l_SpellModOp].end(); ++itr)
                if ((*itr)->type == SPELLMOD_FLAT && (*itr)->mask & l_Mask)
                    l_FlatValue += float((*itr)->value);

            if (l_FlatValue)
            {
                l_SubFlatBuffer << float(l_FlatValue);
                l_SubFlatBuffer << uint8(l_EffectIndex);

                ++l_FlatModifierTypeCount;
            }
        }

        if (l_PctModifierTypeCount)
        {
            ++l_PctModifiersCount;

            l_PctBuffer << uint8(l_SpellModOp);
            l_PctBuffer << uint32(l_PctModifierTypeCount);
            l_PctBuffer.append(l_SubPctBuffer);
        }

        if (l_FlatModifierTypeCount)
        {
            ++l_FlatModifiersCount;

            l_FlatBuffer << uint8(l_SpellModOp);
            l_FlatBuffer << uint32(l_FlatModifierTypeCount);
            l_FlatBuffer.append(l_SubFlatBuffer);
        }

    }

    if (l_PctModifiersCount)
    {
        WorldPacket l_Packet(SMSG_SET_PCT_SPELL_MODIFIER, 4 + l_PctBuffer.size());
        l_Packet << uint32(l_PctModifiersCount);
        l_Packet.append(l_PctBuffer);
        SendDirectMessage(&l_Packet);
    }

    if (l_FlatModifiersCount)
    {
        WorldPacket l_Packet(SMSG_SET_FLAT_SPELL_MODIFIER, 4 + l_FlatBuffer.size());
        l_Packet << uint32(l_FlatModifiersCount);
        l_Packet.append(l_FlatBuffer);
        SendDirectMessage(&l_Packet);
    }
}

void Player::PlayScene(uint32 sceneId, WorldObject* spectator)
{
    if (m_LastPlayedScene)
    {
        m_LastPlayedScene->DestroyForPlayer(this);
        delete m_LastPlayedScene;
        m_LastPlayedScene = NULL;
    }

    m_LastPlayedScene = SceneObject::CreateSceneObject(sceneId, spectator);

    if (m_LastPlayedScene)
        m_LastPlayedScene->SendUpdateToPlayer(this);
}

/// Play standalone scene script on client size
/// @p_ScenePackageID : Scene package ID @ScenePackage.db2
/// @p_PlaybackFlags  : Playback flags (@TODO make some reverse on it)
/// @p_Location       : Scene script start location
/// Return generated Scene instance ID
uint32 Player::PlayStandaloneScene(uint32 p_ScenePackageID, uint32 p_PlaybackFlags, Position p_Location)
{
    SceneScriptPackageEntry const* l_Entry = sSceneScriptPackageStore.LookupEntry(p_ScenePackageID);

    if (!l_Entry)
    {
        sLog->outError(LOG_FILTER_PLAYER, "Player::PlayStandaloneScene => ScenePackage %u doesn't exist", p_ScenePackageID);
        return -1;
    }

    uint64 l_TransportGUID      = 0;
    uint32 l_SceneInstanceID    = sObjectMgr->GetNewStandaloneSceneInstanceID();

    WorldPacket l_PlayScenePacket(SMSG_PLAY_SCENE, 4 + 4 + 4 + 4 + 2 + 16 + 4 + 4 + 4 + 4);
    l_PlayScenePacket << uint32(0);                 ///< SceneID
    l_PlayScenePacket << uint32(p_PlaybackFlags);
    l_PlayScenePacket << uint32(l_SceneInstanceID);
    l_PlayScenePacket << uint32(p_ScenePackageID);
    l_PlayScenePacket.appendPackGUID(l_TransportGUID);
    l_PlayScenePacket << float(p_Location.m_positionX);
    l_PlayScenePacket << float(p_Location.m_positionY);
    l_PlayScenePacket << float(p_Location.m_positionZ);
    l_PlayScenePacket << float(p_Location.m_orientation);

    SendDirectMessage(&l_PlayScenePacket);

    return l_SceneInstanceID;
}

/// Cancel a client-side played standalone scene
/// @p_SceneInstanceID : Scene instance ID
void Player::CancelStandaloneScene(uint32 p_SceneInstanceID)
{
    WorldPacket l_Data(SMSG_CANCEL_SCENE, 4);
    l_Data << uint32(p_SceneInstanceID);
    SendDirectMessage(&l_Data);
}

/// Has battle pet training
bool Player::HasBattlePetTraining()
{
    return HasSpell(119467);
}

/// Get battle pet trap level
uint32 Player::GetBattlePetTrapLevel()
{
    /// Pro Pet Crew
    if (GetAchievementMgr().HasAccountAchieved(6581))
        return 3;     ///< Pristine Pet Trap

    /// Going to Need More Traps
    if (GetAchievementMgr().HasAccountAchieved(6556))
        return 2;      ///< Strong Pet Trap

    return 1; ///< Pet trap
}

/// Compute the unlocked pet battle slot
uint32 Player::GetUnlockedPetBattleSlot()
{
    /// Just a Pup
    if (GetAchievementMgr().HasAccountAchieved(6566))
        return 3;

    /// Newbie
    if (GetAchievementMgr().HasAccountAchieved(7433))
        return 2;

    /// battle pet training
    if (HasBattlePetTraining())
        return 1;

    return 0;
}

/// Summon current pet if any active
void Player::UnsummonCurrentBattlePetIfAny(bool p_Unvolontary)
{
    if (!m_BattlePetSummon)
        return;

    if (!p_Unvolontary)
        m_LastSummonedBattlePet = 0;

    Creature * l_Pet = GetSummonedBattlePet();

    if (l_Pet)
    {
        l_Pet->DespawnOrUnsummon();
        l_Pet->AddObjectToRemoveList();
    }

    m_BattlePetSummon = 0;

    SetGuidValue(PLAYER_FIELD_SUMMONED_BATTLE_PET_GUID, 0);
    SetUInt32Value(UNIT_FIELD_WILD_BATTLE_PET_LEVEL, 0);
}

/// Summon new pet
void Player::SummonBattlePet(uint64 p_JournalID)
{
    if (!IsInWorld())
        return;

    std::vector<BattlePet::Ptr>::iterator l_It = std::find_if(m_BattlePets.begin(), m_BattlePets.end(), [p_JournalID](BattlePet::Ptr & p_Ptr)
    {
        if (p_Ptr && p_Ptr->JournalID == p_JournalID)
            return true;

        return false;
    });

    if (l_It == m_BattlePets.end())
        return;

    BattlePet::Ptr l_BattlePet = (*l_It);

    if (l_BattlePet->Health <= 0)
    {
        UnsummonCurrentBattlePetIfAny(false);
        return;
    }

    BattlePetSpeciesEntry const* l_SpeciesInfo      = sBattlePetSpeciesStore.LookupEntry(l_BattlePet->Species);
    SummonPropertiesEntry const* l_SummonProperties = sSummonPropertiesStore.LookupEntry(3221);

    if (!l_SpeciesInfo || !l_SummonProperties)
        return;

    uint32 l_Team   = GetTeam();
    uint32 l_Phase  = GetPhaseMask();

    WorldLocation l_Position;
    GetClosePoint(l_Position.m_positionX, l_Position.m_positionY, l_Position.m_positionZ, DEFAULT_WORLD_OBJECT_SIZE);

    TempSummon * l_CurrentPet = new Minion(l_SummonProperties, this, false);

    if (!l_CurrentPet->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_UNIT), GetMap(), l_Phase, l_SpeciesInfo->entry, 0, l_Team, l_Position.m_positionX, l_Position.m_positionY, l_Position.m_positionZ, GetOrientation()))
    {
        delete l_CurrentPet;
        l_CurrentPet = 0;
        return;
    }

    l_CurrentPet->SetHomePosition(l_Position);
    l_CurrentPet->SetTempSummonType(TEMPSUMMON_MANUAL_DESPAWN);
    l_CurrentPet->InitStats(0);
    l_CurrentPet->SetOwnerGUID(GetGUID());

    m_LastSummonedBattlePet = GUID_LOPART(l_BattlePet->JournalID);

    SetGuidValue(UNIT_FIELD_CRITTER,                                l_CurrentPet->GetGUID());
    SetUInt32Value(UNIT_FIELD_WILD_BATTLE_PET_LEVEL,                l_BattlePet->Level);
    SetGuidValue(PLAYER_FIELD_SUMMONED_BATTLE_PET_GUID,             l_BattlePet->JournalID);
    SetUInt32Value(PLAYER_FIELD_CURRENT_BATTLE_PET_BREED_QUALITY,   l_BattlePet->Breed);

    l_CurrentPet->SetGuidValue(UNIT_FIELD_BATTLE_PET_COMPANION_GUID,    l_BattlePet->JournalID);
    l_CurrentPet->SetUInt32Value(UNIT_FIELD_WILD_BATTLE_PET_LEVEL,      l_BattlePet->Level);

    if (!l_BattlePet->Name.empty())
    {
        l_CurrentPet->SetUInt32Value(UNIT_FIELD_BATTLE_PET_COMPANION_NAME_TIMESTAMP, l_BattlePet->NameTimeStamp);
        l_CurrentPet->SetName(l_BattlePet->Name);
    }
    else
        l_CurrentPet->SetUInt32Value(UNIT_FIELD_BATTLE_PET_COMPANION_NAME_TIMESTAMP, 0);

    l_CurrentPet->SetUInt32Value(UNIT_FIELD_SHAPESHIFT_FORM, !l_BattlePet->Name.empty());
    l_CurrentPet->SetUInt32Value(UNIT_FIELD_CREATED_BY_SPELL, l_SpeciesInfo->spellId);

    l_CurrentPet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15);
    l_CurrentPet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC);
    l_CurrentPet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_NPC);
    l_CurrentPet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE);
    l_CurrentPet->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
    l_CurrentPet->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
    l_CurrentPet->RemoveFlag(UNIT_FIELD_NPC_FLAGS, UNIT_NPC_FLAG_PETBATTLE);

    GetMap()->AddToMap(l_CurrentPet->ToCreature());

    l_CurrentPet->InitSummon();
    l_CurrentPet->GetMotionMaster()->MoveFollow(this, PET_FOLLOW_DIST, (3 * M_PI) / 2);
    l_CurrentPet->SetSpeed(MOVE_WALK, GetSpeedRate(MOVE_WALK), true);
    l_CurrentPet->SetSpeed(MOVE_RUN, GetSpeedRate(MOVE_RUN), true);

    m_BattlePetSummon = l_CurrentPet->GetGUID();
}

/// Get current summoned battle pet
Creature* Player::GetSummonedBattlePet()
{
    Unit * l_Pet = sObjectAccessor->FindUnit(m_BattlePetSummon);

    return l_Pet ? l_Pet->ToCreature() : NULL;
}

/// Summon last summoned battle pet
void Player::SummonLastSummonedBattlePet()
{
    SummonBattlePet(MAKE_NEW_GUID(m_LastSummonedBattlePet, 0, HIGHGUID_BATTLE_PET));
}

/// Get pet battles
std::vector<std::shared_ptr<BattlePet>> Player::GetBattlePets()
{
    return m_BattlePets;
}

/// Get pet battles
std::shared_ptr<BattlePet> Player::GetBattlePet(uint64 p_JournalID)
{
    std::vector<BattlePet::Ptr>::iterator l_It = std::find_if(m_BattlePets.begin(), m_BattlePets.end(), [p_JournalID](BattlePet::Ptr & p_Ptr)
    {
        if (p_Ptr && p_Ptr->JournalID == p_JournalID)
            return true;

        return false;
    });

    if (l_It == m_BattlePets.end())
        return BattlePet::Ptr();

    return (*l_It);
}

/// Get pet battle combat team
std::shared_ptr<BattlePet> * Player::GetBattlePetCombatTeam()
{
    return m_BattlePetCombatTeam;
}

/// Reload pet battles
void Player::ReloadPetBattles()
{
    SQLTransaction l_Transaction = LoginDatabase.BeginTransaction();

    for (std::vector<BattlePet::Ptr>::iterator l_It = m_BattlePets.begin(); l_It != m_BattlePets.end(); ++l_It)
    {
        BattlePet::Ptr l_Pet = (*l_It);
        l_Pet->Save(l_Transaction);
    }
    
    uint64 l_ThisGUID = GetGUID();
    MS::Utilities::CallBackPtr l_CallBack = std::make_shared<MS::Utilities::Callback>([l_ThisGUID](bool p_Success) -> void ///< p_Success is unused
    {
        if (Player* l_This = HashMapHolder<Player>::Find(l_ThisGUID))
        {
            PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_PETBATTLE_ACCOUNT);
            stmt->setUInt32(0, l_This->GetSession()->GetAccountId());
            l_This->_petBattleJournalCallback = LoginDatabase.AsyncQuery(stmt);
        }
    });

    LoginDatabase.CommitTransaction(l_Transaction, l_CallBack);
}

/// PetBattleCountBattleSpecies
void Player::PetBattleCountBattleSpecies()
{
    PetBattle * l_Battle = sPetBattleSystem->GetBattle(_petBattleId);

    if (!l_Battle)
        return;

    uint32 l_ThisTeamID = l_Battle->Teams[PETBATTLE_TEAM_1]->PlayerGuid == GetGUID() ? PETBATTLE_TEAM_1 : PETBATTLE_TEAM_2;

    std::for_each(m_BattlePets.begin(), m_BattlePets.end(), [l_Battle, l_ThisTeamID](BattlePet::Ptr & p_PetBattle)
    {
        if (!p_PetBattle)
            return;

        if (l_Battle->Teams[l_ThisTeamID]->CapturedSpeciesCount.find(p_PetBattle->Species) == l_Battle->Teams[l_ThisTeamID]->CapturedSpeciesCount.end())
            l_Battle->Teams[l_ThisTeamID]->CapturedSpeciesCount[p_PetBattle->Species] = 0;

        l_Battle->Teams[l_ThisTeamID]->CapturedSpeciesCount[p_PetBattle->Species]++;
    });
}

/// Update battle pet combat team
void Player::UpdateBattlePetCombatTeam()
{
    for (size_t l_CurrentPetSlot = 0; l_CurrentPetSlot < MAX_PETBATTLE_SLOTS; ++l_CurrentPetSlot)
        m_BattlePetCombatTeam[l_CurrentPetSlot] = BattlePet::Ptr();

    uint32 l_UnlockedSlotCount = GetUnlockedPetBattleSlot();

    std::for_each(m_BattlePets.begin(), m_BattlePets.end(), [this, l_UnlockedSlotCount](BattlePet::Ptr & p_BattlePet)
    {
        if (!p_BattlePet)
            return;

        if (p_BattlePet->Slot >= 0 && p_BattlePet->Slot < (int32)l_UnlockedSlotCount)
            m_BattlePetCombatTeam[p_BattlePet->Slot] = p_BattlePet;
    });
}

//////////////////////////////////////////////////////////////////////////
/// Calc Monk Melee Attacks
enum ExpelHarmSpells
{
    SPELL_MONK_STANCE_OF_THE_FIERCE_TIGER = 103985,
    SPELL_MONK_2H_STAFF_OVERRIDE = 108561,
    SPELL_MONK_EXPEL_HARM_DAMAGE = 115129,
    SPELL_MONK_2H_POLEARM_OVERRIDE = 115697,
    SPELL_MONK_MANA_MEDITATION = 121278
};

void Player::CalculateMonkMeleeAttacks(float &p_Low, float &p_High)
{
    Item* l_MainItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND);
    Item* l_OffItem = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);

    float l_MainWeaponMinDamage = 0.0f;
    float l_MainWeaponMaxDamage = 0.0f;
    float l_MainWeaponSpeed = 1.0f;
    float l_OffhandWeaponMinDamage = 0.0f;
    float l_OffhandWeaponMaxDamage = 0.0f;
    float l_OffhandWeaponSpeed = 1.0f;

    if (l_MainItem && l_MainItem->GetTemplate()->Class == ITEM_CLASS_WEAPON && !HasAuraType(SPELL_AURA_MOD_DISARM))
    {
        l_MainWeaponMinDamage = l_MainItem->GetTemplate()->DamageMin;
        l_MainWeaponMaxDamage = l_MainItem->GetTemplate()->DamageMax;
        l_MainWeaponSpeed = float(l_MainItem->GetTemplate()->Delay) / 1000.0f;
    }
    if (l_OffItem && l_OffItem->GetTemplate()->Class == ITEM_CLASS_WEAPON && !HasAuraType(SPELL_AURA_MOD_DISARM))
    {
        l_OffhandWeaponMinDamage = l_OffItem->GetTemplate()->DamageMin;
        l_OffhandWeaponMaxDamage = l_OffItem->GetTemplate()->DamageMax;
        l_OffhandWeaponSpeed = float(l_OffItem->GetTemplate()->Delay) / 1000.0f;
    }

    float l_Dwm = (HasAura(SPELL_MONK_2H_STAFF_OVERRIDE) || HasAura(SPELL_MONK_2H_POLEARM_OVERRIDE)) ? 1.0f : 0.898882275f;
    float l_Offm = (HasAura(SPELL_MONK_2H_STAFF_OVERRIDE) || HasAura(SPELL_MONK_2H_POLEARM_OVERRIDE)) ? 0.0f : 1.0f;

    float l_Offlow = (HasSpell(SPELL_MONK_MANA_MEDITATION)) ? l_MainWeaponMinDamage / 2 / l_MainWeaponSpeed : l_OffhandWeaponMinDamage / 2 / l_OffhandWeaponSpeed;
    float l_Offhigh = (HasSpell(SPELL_MONK_MANA_MEDITATION)) ? l_MainWeaponMaxDamage / 2 / l_MainWeaponSpeed : l_OffhandWeaponMaxDamage / 2 / l_OffhandWeaponSpeed;

    p_Low = (l_Dwm * (l_MainWeaponMinDamage / l_MainWeaponSpeed + l_Offm * l_Offlow) + GetTotalAttackPowerValue(WeaponAttackType::BaseAttack) / 3.5f - 1);
    p_High = (l_Dwm * (l_MainWeaponMaxDamage / l_MainWeaponSpeed + l_Offm * l_Offhigh) + GetTotalAttackPowerValue(WeaponAttackType::BaseAttack) / 3.5f + 1);
}

//////////////////////////////////////////////////////////////////////////
/// ToyBox
void Player::_LoadToyBox(PreparedQueryResult p_Result)
{
    if (!p_Result)
        return;

    do
    {
        Field* l_Fields = p_Result->Fetch();
        uint32 l_ItemID = l_Fields[0].GetUInt32();
        bool l_IsFavorite = l_Fields[1].GetBool();

        if (!HasToy(l_ItemID))
        {
            PlayerToy l_PlayerToy = PlayerToy(l_ItemID, l_IsFavorite);
            m_PlayerToys.insert(std::make_pair(l_ItemID, l_PlayerToy));
        }
    }
    while (p_Result->NextRow());

    uint32 l_Count = 0;
    for (PlayerToys::iterator l_Toy = m_PlayerToys.begin(); l_Toy != m_PlayerToys.end(); ++l_Toy)
    {
        SetDynamicValue(PLAYER_DYNAMIC_FIELD_TOYS, l_Count, l_Toy->second.m_ItemID);
        ++l_Count;
    }
}

void Player::SendToyBox()
{
    uint32 l_ToyCount = m_PlayerToys.size();

    WorldPacket l_Data(SMSG_ACCOUNT_TOYS_UPDATE, 2 * 1024);
    l_Data.WriteBit(true);      // IsFullUpdate

    l_Data << uint32(l_ToyCount);
    l_Data << uint32(l_ToyCount);

    for (auto l_Toy : m_PlayerToys)
        l_Data << uint32(l_Toy.second.m_ItemID);

    for (auto l_Toy : m_PlayerToys)
        l_Data.WriteBit(l_Toy.second.m_IsFavorite);

    SendDirectMessage(&l_Data);
}

void Player::AddNewToyToBox(uint32 p_ItemID)
{
    /// Save toys to database only for live realms
    if (sWorld->CanBeSaveInLoginDatabase())
    {
        PreparedStatement* l_Statement = LoginDatabase.GetPreparedStatement(LOGIN_INS_ACCOUNT_TOYS);
        l_Statement->setUInt32(0, GetSession()->GetAccountId());
        l_Statement->setUInt32(1, p_ItemID);
        l_Statement->setBool(2, false);
        LoginDatabase.Execute(l_Statement);
    }

    if (!HasToy(p_ItemID))
    {
        UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COLLECT_TOYS, 1, 0, 0, nullptr);

        PlayerToy l_PlayerToy = PlayerToy(p_ItemID, false);
        m_PlayerToys.insert(std::make_pair(p_ItemID, l_PlayerToy));

        uint32 l_ToySize = m_PlayerToys.size();
        SetDynamicValue(PLAYER_DYNAMIC_FIELD_TOYS, l_ToySize, p_ItemID);
    }
}

void Player::SetFavoriteToy(bool p_Apply, uint32 p_ItemID)
{
    PreparedStatement* l_Statement = LoginDatabase.GetPreparedStatement(LOGIN_UPD_TOY_FAVORITE);
    l_Statement->setBool(0, p_Apply);
    l_Statement->setUInt32(1, GetSession()->GetAccountId());
    l_Statement->setUInt32(2, p_ItemID);
    LoginDatabase.Execute(l_Statement);

    WorldPacket l_Data(SMSG_ACCOUNT_TOYS_UPDATE);
    l_Data.WriteBit(false);     // IsFullUpdate

    l_Data << uint32(1);
    l_Data << uint32(1);
    l_Data << uint32(p_ItemID);
    l_Data.WriteBit(p_Apply);   // IsFavorite

    SendDirectMessage(&l_Data);

    if (PlayerToy* l_PlayerToy = GetToy(p_ItemID))
        l_PlayerToy->m_IsFavorite = p_Apply;
}
//////////////////////////////////////////////////////////////////////////

void Player::_LoadBossLooted(PreparedQueryResult p_Result)
{
    if (!p_Result)
        return;

    m_BossLooted.clear();

    do
    {
        Field* l_Fields = p_Result->Fetch();
        uint32 l_BossEntry = l_Fields[0].GetUInt32();
        uint32 l_DisplayID = l_Fields[1].GetUInt32();

        uint64 l_Value = l_BossEntry | ((uint64)l_DisplayID << 32);

        if (m_BossLooted.find(l_Value) != m_BossLooted.end())
            continue;

        m_BossLooted.insert(l_Value);
    }
    while (p_Result->NextRow());
}

bool Player::BossAlreadyLooted(Creature* p_Creature) const
{
    if (p_Creature == nullptr)
        return false;

    uint64 l_Value = p_Creature->GetEntry() | ((uint64)p_Creature->GetNativeDisplayId() << 32);

    if (m_BossLooted.find(l_Value) == m_BossLooted.end())
        return false;

    return true;
}

void Player::AddBossLooted(Creature* p_Creature)
{
    if (p_Creature == nullptr)
        return;

    uint64 l_Value = p_Creature->GetEntry() | ((uint64)p_Creature->GetNativeDisplayId() << 32);

    if (m_BossLooted.find(l_Value) != m_BossLooted.end())
        return;

    m_BossLooted.insert(l_Value);

    PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_INS_BOSS_LOOTED);
    l_Statement->setUInt32(0, GetGUIDLow());
    l_Statement->setUInt32(1, p_Creature->GetEntry());
    l_Statement->setUInt32(2, p_Creature->GetNativeDisplayId());
    CharacterDatabase.Execute(l_Statement);
}

bool Player::HasUnlockedReagentBank()
{
    return HasFlag(PLAYER_FIELD_PLAYER_FLAGS_EX, PLAYER_FLAGS_EX_REAGENT_BANK_UNLOCKED);
}

void Player::UnlockReagentBank()
{
    SetFlag(PLAYER_FIELD_PLAYER_FLAGS_EX, PLAYER_FLAGS_EX_REAGENT_BANK_UNLOCKED);
}

uint32 Player::GetFreeReagentBankSlot() const
{
    for (uint8 l_I = REAGENT_BANK_SLOT_BAG_START; l_I < REAGENT_BANK_SLOT_BAG_END; ++l_I)
    {
        if (!GetItemByPos(INVENTORY_SLOT_BAG_0, l_I))
            return l_I;
    }

    return REAGENT_BANK_SLOT_BAG_END;
}

MS::Garrison::Manager * Player::GetGarrison()
{
    return m_Garrison;
}

void Player::CreateGarrison()
{
    if (m_Garrison)
        return;

    m_Garrison = new MS::Garrison::Manager(this);
    m_Garrison->Create();
}

bool Player::IsInGarrison() const
{
    if (!m_Garrison || !m_Garrison->GetGarrisonSiteLevelEntry())
        return false;

    if (GetMapId() == m_Garrison->GetGarrisonSiteLevelEntry()->MapID)
        return true;

    return false;
}

bool Player::IsInShipyard() const
{
    return GetShipyardMapID() == GetMapId(); ///< Comparison of integers of different signs: 'int32' (aka 'int') and 'uint32' (aka 'unsigned int')
}

int32 Player::GetGarrisonMapID() const
{
    if (!m_Garrison)
        return -1;

    return m_Garrison->GetGarrisonSiteLevelEntry()->MapID;
}

int32 Player::GetShipyardMapID() const
{
    if (!m_Garrison)
        return -1;

    return m_Garrison->GetShipyardMapId();
}

void Player::DeleteGarrison()
{
    if (!m_Garrison)
        return;

    SQLTransaction l_Transaction = CharacterDatabase.BeginTransaction();
    m_Garrison->DeleteFromDB(GetGUID(), l_Transaction);
    CharacterDatabase.CommitTransaction(l_Transaction);

    if (IsInGarrison())
    {
        if (GetTeamId() == TEAM_ALLIANCE)
            TeleportTo(0, -8866.55f, 671.93f, 97.90f, 5.31f);
        else if (GetTeamId() == TEAM_HORDE)
            TeleportTo(1, 1577.30f, -4453.64f, 15.68f, 1.84f);
    }

    delete m_Garrison;
    m_Garrison = nullptr;
}

uint32 Player::GetPlotInstanceID() const
{
    if (m_Garrison == nullptr)
        return 0;

    return m_Garrison->GetPlot(m_positionX, m_positionY, m_positionZ).PlotInstanceID;
}

Stats Player::GetPrimaryStat() const
{
    int8 magicNumber = -1;
    if (ChrSpecializationsEntry const* spec = sChrSpecializationsStore.LookupEntry(GetSpecializationId()))
        magicNumber = spec->MainStat;
    else if (ChrClassesEntry const* playerClass = sChrClassesStore.LookupEntry(getClass()))
        magicNumber = playerClass->MainStat;

    // WTF is Blizzard doing ????
    switch (magicNumber)
    {
        case 0:
        case 1:
            return STAT_INTELLECT;
        case 2:
        case 3:
            return STAT_AGILITY;
        case 4:
        case 5:
        default:
            return STAT_STRENGTH;
    }
}

/*
 *          WARNING !!!!!!
 *
 *
 *
 *  Never use _ApplyItemBonuses for rescaling, use those the functions below, unless you know how it works and trust me you dont
 *
 */

ScalingStatDistributionEntry const* Player::GetSSDForItem(Item const* p_Item) const
{
    if (!p_Item)
        return nullptr;

    uint32 l_SSDID = p_Item->GetTemplate()->ScalingStatDistribution;

    std::vector<uint32> const& l_ItemBonuses = p_Item->GetAllItemBonuses();
    for (auto l_Bonus : l_ItemBonuses)
    {
        if (!l_Bonus)
            continue;

        std::vector<ItemBonusEntry const*> const* l_ItemBonus = GetItemBonusesByID(l_Bonus);
        if (!l_ItemBonus)
            continue;

        for (uint32 i = 0; i < l_ItemBonus->size(); i++)
        {
            ItemBonusEntry const* l_ItemSubBonus = (*l_ItemBonus)[i];
            if (!l_ItemSubBonus)
                break;

            if (l_ItemSubBonus->Type == ITEM_BONUS_MODIFY_SSD_ID)
            {
                l_SSDID = l_ItemSubBonus->Value[0];
                break;
            }
        }
    }

    return sScalingStatDistributionStore.LookupEntry(l_SSDID);
}

uint32 Player::GetEquipItemLevelFor(ItemTemplate const* itemProto, Item const* item, bool p_IgnorePvPModifiers /* = false */, bool p_ForcePvPItemLevel /* = false */) const
{
    uint32 ilvl = itemProto->ItemLevel;

    if (itemProto->Quality == ITEM_QUALITY_HEIRLOOM)
        if (ScalingStatDistributionEntry const* ssd = GetSSDForItem(item))
            if (uint32 heirloomIlvl = GetHeirloomItemLevel(ssd->CurveProperties, std::max(std::min(ssd->MaxLevel, (uint32)getLevel()), ssd->MinLevel)))
                ilvl = heirloomIlvl;

    if (item)
        ilvl += item->GetItemLevelBonusFromItemBonuses();

    if (itemProto->PvPScalingLevel && !p_IgnorePvPModifiers)
        if (p_ForcePvPItemLevel || (GetMap() && GetMap()->IsBattlegroundOrArena()) || (IsInPvPCombat() && m_deathState != JUST_DIED))
            ilvl += itemProto->PvPScalingLevel;

    if (uint32 minItemLevel = GetUInt32Value(UNIT_FIELD_MIN_ITEM_LEVEL))
        if (ilvl < minItemLevel && ilvl > GetUInt32Value(UNIT_FIELD_MIN_ITEM_LEVEL_CUTOFF))
            ilvl = minItemLevel;

    if (uint32 maxItemLevel = GetUInt32Value(UNIT_FIELD_MAX_ITEM_LEVEL))
        ilvl = std::min(ilvl, maxItemLevel);

    if (!(GetMap()->IsBattlegroundOrArena() && GetBattleground() && GetBattleground()->IsWargame()))
    {
        if (itemProto->Flags3 & ItemFlags3::ITEM_FLAG3_WARGAME_ONLY)
            ilvl = 1;
    }

    return ilvl;
}

void Player::RescaleItemTo(uint8 slot, uint32 ilvl)
{
    if (slot >= EQUIPMENT_SLOT_END)
        return;

    Item* item = m_items[slot];

    if (!item)
        return;

    ItemTemplate const* proto = item->GetTemplate();

    if(!proto)
        return;

    _ApplyItemModifications(item, slot, true, proto->ItemLevel);
    _ApplyItemBonuses(item, slot, true, proto->ItemLevel);
    m_itemScale[slot] = proto->ItemLevel;
    _ApplyItemModifications(item, slot, true, ilvl);
    _ApplyItemBonuses(item, slot, true, ilvl);
    m_itemScale[slot] = ilvl;
}

void Player::RescaleAllItemsIfNeeded(bool p_KeepHPPct /* = false */)
{
    float l_HealthPct = GetHealthPct();
    bool l_HasAnythingChanged = false;

    for (uint8 l_I = 0; l_I < EQUIPMENT_SLOT_END; ++l_I)
    {
        if (Item* l_Item = m_items[l_I])
        {
            if (l_Item->CantBeUse() || !CanUseAttackType(GetAttackBySlot(l_I)) || l_Item->GetTemplate() == nullptr)
                continue;

            uint32 ilvl = GetEquipItemLevelFor(l_Item->GetTemplate(), m_items[l_I]);
            if (m_itemScale[l_I] != ilvl)
            {
                RescaleItemTo(l_I, ilvl);
                l_HasAnythingChanged = true;
            }
        }
    }

    if (l_HasAnythingChanged)
    {
        if (p_KeepHPPct)
        {
            int32 l_Health = std::max(1, int32(l_HealthPct * (float)GetMaxHealth() / 100.0f));
            SetHealth(l_Health);
        }

        UpdateItemLevel();
    }
}

void Player::CutOffItemLevel(bool p_RescaleItems)
{
    Map* l_Map = GetMap();
    if (!l_Map)
        return;

    uint32 l_StartsWith = 0, l_MinLevel = 0, l_MaxLevel = 0;

    if (l_Map->IsBattlegroundOrArena())
    {
        l_StartsWith = sWorld->getIntConfig(CONFIG_PVP_ITEM_LEVEL_CUTOFF);
        l_MinLevel = sWorld->getIntConfig(CONFIG_PVP_ITEM_LEVEL_MIN);
        l_MaxLevel = sWorld->getIntConfig(CONFIG_PVP_ITEM_LEVEL_MAX);
    }
    else if (l_Map->GetDifficultyID() == DifficultyChallenge && l_Map->IsDungeon())
    {
        l_MaxLevel = sWorld->getIntConfig(CONFIG_CHALLENGE_MODE_ITEM_LEVEL_MAX);
    }

    UpdateItemLevelCutOff(l_StartsWith, l_MinLevel, l_MaxLevel, p_RescaleItems);
}

bool Player::UpdateItemLevelCutOff(uint32 p_StartsWith, uint32 p_MinLevel, uint32 p_MaxLevel, bool p_RescaleItems)
{
    if ((!p_MaxLevel && p_MinLevel > p_MaxLevel) || p_StartsWith > p_MaxLevel)
        return false;

    SetUInt32Value(UNIT_FIELD_MIN_ITEM_LEVEL_CUTOFF, p_StartsWith);
    SetUInt32Value(UNIT_FIELD_MIN_ITEM_LEVEL, p_MinLevel);
    SetUInt32Value(UNIT_FIELD_MAX_ITEM_LEVEL, p_MaxLevel);

    if (p_RescaleItems)
        RescaleAllItemsIfNeeded(true);

    return true;
}

void Player::SetInPvPCombat(bool set)
{
    if (m_pvpCombat == set)
        return;

    m_pvpCombat = set;

    if (m_pvpCombat)
        OnEnterPvPCombat();
}

void Player::OnEnterPvPCombat()
{
    RescaleAllItemsIfNeeded(true);
}

void Player::UpdatePvP(uint32 diff)
{
    if (!m_PvPCombatTimer || !IsInPvPCombat())
        return;

    if (m_PvPCombatTimer <= diff)
    {
        SetInPvPCombat(false);
        OnLeavePvPCombat();
        m_PvPCombatTimer = 0;
    }
    else
        m_PvPCombatTimer -= diff;
}

void Player::OnLeavePvPCombat()
{
    RescaleAllItemsIfNeeded(true);
}

/// Get pet battle combat team size
uint32 Player::GetBattlePetCombatSize()<--- The function 'GetBattlePetCombatSize' is never used.
{
    uint32 l_Count = 0;

    for (size_t l_CurrentPetSlot = 0; l_CurrentPetSlot < MAX_PETBATTLE_SLOTS; ++l_CurrentPetSlot)
        if (m_BattlePetCombatTeam[l_CurrentPetSlot])
            l_Count++;

    return l_Count;
}

/// Load pet battle async callback
bool Player::_LoadPetBattles(PreparedQueryResult&& p_Result)
{
    m_BattlePets.clear();

    if (!p_Result)
    {
        bool l_Add = false;

        for (uint32 l_I = 0; l_I < m_OldPetBattleSpellToMerge.size(); l_I++)
        {
            BattlePet l_BattlePet;
            l_BattlePet.Slot            = PETBATTLE_NULL_SLOT;
            l_BattlePet.NameTimeStamp   = 0;
            l_BattlePet.Species         = m_OldPetBattleSpellToMerge[l_I].second;
            l_BattlePet.DisplayModelID  = 0;
            l_BattlePet.Flags           = 0;

            if (BattlePetTemplate const* l_Template = sObjectMgr->GetBattlePetTemplate(m_OldPetBattleSpellToMerge[l_I].second))
            {
                l_BattlePet.Breed   = l_Template->Breed;
                l_BattlePet.Quality = l_Template->Quality;
                l_BattlePet.Level   = l_Template->Level;
            }
            else
            {
                l_BattlePet.Breed   = 3;
                l_BattlePet.Quality = BATTLEPET_QUALITY_COMMON;
                l_BattlePet.Level   = 1;
            }

            /// Calculate XP for level
            l_BattlePet.XP = 0;

            if (l_BattlePet.Level > 1 && l_BattlePet.Level < 100)
                l_BattlePet.XP = sGtBattlePetXPStore.LookupEntry(l_BattlePet.Level - 2)->value * sGtBattlePetXPStore.LookupEntry(100 + l_BattlePet.Level - 2)->value;

            /// Calculate stats
            l_BattlePet.UpdateStats();
            l_BattlePet.Health = l_BattlePet.InfoMaxHealth;
            l_BattlePet.AddToPlayer(this);

            l_Add = true;
        }

        m_OldPetBattleSpellToMerge.clear();

        if (l_Add)
            return false;
    }

    for (size_t l_CurrentPetSlot = 0; l_CurrentPetSlot < MAX_PETBATTLE_SLOTS; ++l_CurrentPetSlot)
        m_BattlePetCombatTeam[l_CurrentPetSlot] = BattlePet::Ptr();

    m_BattlePets.resize(p_Result ? p_Result->GetRowCount() : 0);
    uint32 l_UnlockedSlotCount = GetUnlockedPetBattleSlot();

    if (l_UnlockedSlotCount > 0)
        SetFlag(PLAYER_FIELD_PLAYER_FLAGS, PLAYER_FLAGS_HAS_BATTLE_PET_TRAINING);

    std::vector<uint32> l_AlreadyKnownPet;

    if (p_Result && p_Result->GetRowCount())
    {
        size_t l_PetID = 0;

        do
        {
            if (l_PetID > m_BattlePets.size())
                continue;

            m_BattlePets[l_PetID] = BattlePet::Ptr(new BattlePet());
            m_BattlePets[l_PetID]->Load(p_Result->Fetch());

            if (m_BattlePets[l_PetID]->Slot >= 0 && m_BattlePets[l_PetID]->Slot < (int32)l_UnlockedSlotCount)
                m_BattlePetCombatTeam[m_BattlePets[l_PetID]->Slot] = m_BattlePets[l_PetID];

            l_AlreadyKnownPet.push_back(m_BattlePets[l_PetID]->Species);

            BattlePetSpeciesEntry const* l_SpeciesEntry = sBattlePetSpeciesStore.LookupEntry(m_BattlePets[l_PetID]->Species);
            if (l_SpeciesEntry != nullptr && !HasSpell(l_SpeciesEntry->spellId))
                addSpell(l_SpeciesEntry->spellId, true, true, false, false, false, false, false);

            ++l_PetID;
        } while (p_Result->NextRow());
    }

    bool l_OldPetAdded = false;
    for (uint32 l_I = 0; l_I < m_OldPetBattleSpellToMerge.size(); l_I++)
    {
        if (std::find(l_AlreadyKnownPet.begin(), l_AlreadyKnownPet.end(), m_OldPetBattleSpellToMerge[l_I].second) != l_AlreadyKnownPet.end())
            continue;

        l_OldPetAdded = true;

        BattlePet l_BattlePet;
        l_BattlePet.Slot            = PETBATTLE_NULL_SLOT;
        l_BattlePet.NameTimeStamp   = 0;
        l_BattlePet.Species         = m_OldPetBattleSpellToMerge[l_I].second;
        l_BattlePet.DisplayModelID  = 0;
        l_BattlePet.Flags           = 0;

        if (BattlePetTemplate const* temp = sObjectMgr->GetBattlePetTemplate(m_OldPetBattleSpellToMerge[l_I].second))
        {
            l_BattlePet.Breed   = temp->Breed;
            l_BattlePet.Quality = temp->Quality;
            l_BattlePet.Level   = temp->Level;
        }
        else
        {
            l_BattlePet.Breed   = 3;
            l_BattlePet.Quality = BATTLEPET_QUALITY_COMMON;
            l_BattlePet.Level   = 1;
        }

        /// Calculate XP for level
        l_BattlePet.XP = 0;

        if (l_BattlePet.Level > 1 && l_BattlePet.Level < 100)
            l_BattlePet.XP = sGtBattlePetXPStore.LookupEntry(l_BattlePet.Level - 2)->value * sGtBattlePetXPStore.LookupEntry(100 + l_BattlePet.Level - 2)->value;

        /// Calculate stats
        l_BattlePet.UpdateStats();
        l_BattlePet.Health = l_BattlePet.InfoMaxHealth;

        l_BattlePet.AddToPlayer(this);

        ///removeSpell(m_OldPetBattleSpellToMerge[l_I].first);
    }

    m_OldPetBattleSpellToMerge.clear();

    if (l_OldPetAdded)
        return false;

    GetSession()->SendBattlePetJournal();

    return true;
}

//////////////////////////////////////////////////////////////////////////
/// SpellCharges
void Player::SendSpellCharges()
{
    WorldPacket l_Data(SMSG_SEND_SPELL_CHARGES, 4 + m_CategoryCharges.size() * 9);

    l_Data << uint32(m_CategoryCharges.size());

    Clock::time_point l_Now = Clock::now();
    for (auto l_CategoryCharge : m_CategoryCharges)
    {
        if (!l_CategoryCharge.second.empty())
        {
            std::chrono::milliseconds l_CooldownDuration = std::chrono::duration_cast<std::chrono::milliseconds>(l_CategoryCharge.second.front().RechargeEnd - l_Now);
            if (l_CooldownDuration.count() <= 0)
                continue;

            l_Data << uint32(l_CategoryCharge.first);
            l_Data << uint32(l_CooldownDuration.count());
            l_Data << uint8(l_CategoryCharge.second.size());
        }
    }
    SendDirectMessage(&l_Data);
}

void Player::SendSetSpellCharges(SpellCategoryEntry const* p_ChargeCategoryEntry)<--- The function 'SendSetSpellCharges' is never used.
{
    if (!p_ChargeCategoryEntry)
        return;

    Clock::time_point l_Now = Clock::now(); ///< l_Now is unused<--- Variable 'l_Now' is assigned a value that is never used.
    auto l_Itr = m_CategoryCharges.find(p_ChargeCategoryEntry->Id);
    if (l_Itr != m_CategoryCharges.end() && !l_Itr->second.empty())
    {
        uint32 l_ConsumedCharges = l_Itr->second.size();
        bool   l_IsPet = false;

        WorldPacket l_Data(SMSG_SET_SPELL_CHARGES);
        l_Data << uint32(p_ChargeCategoryEntry->Id);
        l_Data << uint32(p_ChargeCategoryEntry->ChargeRecoveryTime);
        l_Data << uint8(l_ConsumedCharges);
        l_Data.WriteBit(l_IsPet);
        l_Data.FlushBits();


        if (l_IsPet)
        {
            l_Data << uint32(0);    ///< unk
            l_Data << uint32(0);    ///< unk
        }

        SendDirectMessage(&l_Data);
    }
}

void Player::UpdateCharges()
{
    Clock::time_point l_Now = Clock::now();

    for (auto& l_CategoryCharge : m_CategoryCharges)
    {
        std::deque<ChargeEntry>& l_ChargeRefreshTimes = l_CategoryCharge.second;

        while (!l_ChargeRefreshTimes.empty() && l_ChargeRefreshTimes.front().RechargeEnd <= l_Now)
        {
            l_ChargeRefreshTimes.pop_front();
            SendSpellCharges();
        }
    }
}

bool Player::ConsumeCharge(SpellCategoryEntry const* p_ChargeCategoryEntry)
{
    if (!p_ChargeCategoryEntry)
        return false;

    int32 l_ChargeRecovery = GetChargeRecoveryTime(p_ChargeCategoryEntry);
    if (l_ChargeRecovery > 0 && GetMaxCharges(p_ChargeCategoryEntry) > 0)
    {
        Clock::time_point l_RecoveryStart;
        std::deque<ChargeEntry>& l_Charges = m_CategoryCharges[p_ChargeCategoryEntry->Id];

        if (l_Charges.empty())
            l_RecoveryStart = Clock::now();
        else
            l_RecoveryStart = l_Charges.back().RechargeEnd;

        l_Charges.emplace_back(l_RecoveryStart, std::chrono::milliseconds(l_ChargeRecovery));

        return true;
    }

    return false;
}

void Player::ReduceChargeCooldown(SpellCategoryEntry const* p_ChargeCategoryEntry, uint64 p_Reductiontime)
{
    if (!p_ChargeCategoryEntry)
        return;

    Clock::time_point l_Now = Clock::now();

    auto l_Itr = m_CategoryCharges.find(p_ChargeCategoryEntry->Id);
    if (l_Itr != m_CategoryCharges.end() && !l_Itr->second.empty())
    {
        Clock::time_point l_NewRechargeEnd = l_Itr->second.back().RechargeEnd - std::chrono::milliseconds(p_Reductiontime);
        if (l_NewRechargeEnd > l_Now)
            l_Itr->second.back().RechargeEnd = l_NewRechargeEnd;
        else
            l_Itr->second.pop_back();

        SendSpellCharges();
    }
}

void Player::RestoreCharge(SpellCategoryEntry const* p_ChargeCategoryEntry)
{
    if (!p_ChargeCategoryEntry)
        return;

    auto l_Itr = m_CategoryCharges.find(p_ChargeCategoryEntry->Id);
    if (l_Itr != m_CategoryCharges.end() && !l_Itr->second.empty())
    {
        l_Itr->second.pop_back();

        uint32 l_ConsumedCharges = l_Itr->second.size();

        bool l_IsPet = false;

        WorldPacket l_Data(SMSG_SET_SPELL_CHARGES);
        l_Data << uint32(p_ChargeCategoryEntry->Id);
        l_Data << uint32(p_ChargeCategoryEntry->ChargeRecoveryTime);
        l_Data << uint8(l_ConsumedCharges);
        l_Data.WriteBit(l_IsPet);
        l_Data.FlushBits();

        if (l_IsPet)
        {
            l_Data << uint32(0);    ///< unk
            l_Data << uint32(0);    ///< unk
        }

        SendDirectMessage(&l_Data);
    }
}

void Player::ResetCharges(SpellCategoryEntry const* p_ChargeCategoryEntry)
{
    if (!p_ChargeCategoryEntry)
        return;

    auto l_Itr = m_CategoryCharges.find(p_ChargeCategoryEntry->Id);
    if (l_Itr != m_CategoryCharges.end())
    {
        m_CategoryCharges.erase(l_Itr);

        WorldPacket l_Data(SMSG_CLEAR_SPELL_CHARGES);
        l_Data << int32(p_ChargeCategoryEntry->Id);
        l_Data.WriteBit(false); ///< IsPet
        l_Data.FlushBits();
        SendDirectMessage(&l_Data);
    }
}

void Player::ResetAllCharges()
{
    m_CategoryCharges.clear();

    WorldPacket l_Data(SMSG_CLEAR_ALL_SPELL_CHARGES);
    l_Data.appendPackGUID(GetGUID());
    SendDirectMessage(&l_Data);
}

bool Player::HasCharge(SpellCategoryEntry const* p_ChargeCategoryEntry) const
{
    if (!p_ChargeCategoryEntry)
        return true;

    // Check if the spell is currently using charges (untalented warlock Dark Soul)
    int32 l_MaxCharges = GetMaxCharges(p_ChargeCategoryEntry);
    if (l_MaxCharges <= 0)
        return true;

    auto l_Itr = m_CategoryCharges.find(p_ChargeCategoryEntry->Id);
    return l_Itr == m_CategoryCharges.end() || int32(l_Itr->second.size()) < l_MaxCharges;
}

uint32 Player::GetMaxCharges(SpellCategoryEntry const* p_ChargeCategoryEntry) const
{
    if (!p_ChargeCategoryEntry)
        return 0;

    uint32 l_MaxCharge = p_ChargeCategoryEntry->MaxCharges;

    l_MaxCharge += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_MAX_CHARGES, p_ChargeCategoryEntry->Id);

    return l_MaxCharge;
}

int32 Player::GetChargeRecoveryTime(SpellCategoryEntry const* p_ChargeCategoryEntry) const
{
    if (!p_ChargeCategoryEntry)
        return 0;

    float l_RecoveryTime = p_ChargeCategoryEntry->ChargeRecoveryTime;

    l_RecoveryTime += float(GetTotalAuraModifierByMiscValue(SPELL_AURA_CHARGE_RECOVERY_MOD, p_ChargeCategoryEntry->Id));
    l_RecoveryTime *= GetTotalAuraMultiplierByMiscValue(SPELL_AURA_CHARGE_RECOVERY_MULTIPLIER, p_ChargeCategoryEntry->Id);

    if (HasAuraType(SPELL_AURA_CHARGE_RECOVERY_AFFECTED_BY_HASTE))
        l_RecoveryTime *= GetFloatValue(UNIT_FIELD_MOD_CASTING_SPEED);

    if (HasAuraType(SPELL_AURA_CHARGE_RECOVERY_AFFECTED_BY_HASTE_REGEN))
        l_RecoveryTime *= GetFloatValue(UNIT_FIELD_MOD_HASTE_REGEN);

    return int32(std::floor(l_RecoveryTime));
}

//////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////
/// ChallengesMode
void Player::_LoadCompletedChallenges(PreparedQueryResult&& p_Result)
{
    if (!p_Result)
        return;

    do
    {
        CompletedChallenge l_Challenge;

        Field* l_Field = p_Result->Fetch();
        uint32 l_MapID = l_Field[0].GetUInt32();
        l_Challenge.m_BestTime = l_Field[1].GetUInt32();
        l_Challenge.m_LastTime = l_Field[2].GetUInt32();
        l_Challenge.m_BestMedal = l_Field[3].GetUInt8();
        l_Challenge.m_BestMedalDate = l_Field[4].GetUInt32();

        m_CompletedChallenges.insert(std::make_pair(l_MapID, l_Challenge));
    }
    while (p_Result->NextRow());
}

bool Player::HasChallengeCompleted(uint32 p_MapID) const
{
    if (m_CompletedChallenges.find(p_MapID) == m_CompletedChallenges.end())
        return false;

    return true;
}

CompletedChallenge* Player::GetCompletedChallenge(uint32 p_MapID)
{
    if (m_CompletedChallenges.find(p_MapID) == m_CompletedChallenges.end())
        return nullptr;

    return &m_CompletedChallenges[p_MapID];
}

void Player::AddCompletedChallenge(uint32 p_MapID, CompletedChallenge p_Challenge)
{
    /// Already completed
    if (m_CompletedChallenges.find(p_MapID) != m_CompletedChallenges.end())
        return;

    m_CompletedChallenges.insert(std::make_pair(p_MapID, p_Challenge));
}
//////////////////////////////////////////////////////////////////////////

void Player::ApplyOnBagsItems(std::function<bool(Player*, Item*, uint8, uint8)>&& p_Function)
{
    for (uint32 l_I = INVENTORY_SLOT_ITEM_START; l_I < INVENTORY_SLOT_ITEM_END; l_I++)
    {
        if (Item* l_Item = GetItemByPos(INVENTORY_SLOT_BAG_0, l_I))
        {
            if (!p_Function(this, l_Item, INVENTORY_SLOT_BAG_0, l_I))
                return;
        }
    }

    for (uint32 l_I = INVENTORY_SLOT_BAG_START; l_I < INVENTORY_SLOT_BAG_END; ++l_I)
    {
        if (Bag* l_Bag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, l_I))
        {
            for (uint32 l_J = 0; l_J < l_Bag->GetBagSize(); ++l_J)
            {
                if (Item* l_Item = GetItemByPos(l_I, l_J))
                {
                    if (!p_Function(this, l_Item, l_I, l_J))
                        return;
                }
            }
        }
    }
}

void Player::ApplyOnBankItems(std::function<bool(Player*, Item*, uint8, uint8)>&& p_Function)
{
    for (uint32 l_I = BANK_SLOT_ITEM_START; l_I < BANK_SLOT_ITEM_END; l_I++)
    {
        if (Item* l_Item = GetItemByPos(INVENTORY_SLOT_BAG_0, l_I))
        {
            if (!p_Function(this, l_Item, INVENTORY_SLOT_BAG_0, l_I))
                return;
        }
    }

    for (uint32 l_I = BANK_SLOT_BAG_START; l_I < BANK_SLOT_BAG_END; ++l_I)
    {
        if (Bag* l_Bag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0, l_I))
        {
            for (uint32 l_J = 0; l_J < l_Bag->GetBagSize(); ++l_J)
            {
                if (Item* l_Item = GetItemByPos(l_I, l_J))
                {
                    if (!p_Function(this, l_Item, l_I, l_J))
                        return;
                }
            }
        }
    }
}

void Player::ApplyOnReagentBankItems(std::function<bool(Player*, Item*, uint8, uint8)>&& p_Function)<--- The function 'ApplyOnReagentBankItems' is never used.
{
    for (uint32 l_I = REAGENT_BANK_SLOT_BAG_START; l_I < REAGENT_BANK_SLOT_BAG_END; ++l_I)
    {
        if (Item* l_Item = GetItemByPos(INVENTORY_SLOT_BAG_0, l_I))
        {
            if (!p_Function(this, l_Item, INVENTORY_SLOT_BAG_0, l_I))
                return;
        }
    }
}

void Player::_LoadDailyLootsCooldowns(PreparedQueryResult&& p_Result)
{
    if (!p_Result)
        return;

    do
    {
        CompletedChallenge l_Challenge;

        Field* l_Field = p_Result->Fetch();
        uint32 l_ID = l_Field[0].GetUInt32();

        if (!m_DailyLootsCooldowns.count(l_ID))
            m_DailyLootsCooldowns.insert(l_ID);
    }
    while (p_Result->NextRow());
}

void Player::ResetDailyLoots()
{
    m_DailyLootsCooldowns.clear();
}

void Player::AddDailyLootCooldown(uint32 p_Entry)
{
    /// If not, already in database
    if (!m_DailyLootsCooldowns.count(p_Entry))
    {
        m_DailyLootsCooldowns.insert(p_Entry);

        PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_INS_DAILY_LOOT_COOLDOWNS);
        l_Statement->setUInt32(0, GetGUIDLow());
        l_Statement->setUInt32(1, p_Entry);
        CharacterDatabase.Execute(l_Statement);
    }
}

bool Player::AddHeirloom(HeirloomEntry const* p_HeirloomEntry, uint8 p_UpgradeLevel, bool p_UseShopGroupRealmMask)
{
    if (HasHeirloom(p_HeirloomEntry))
        return false;

    uint32 l_Index = GetDynamicValues(PLAYER_DYNAMIC_FIELD_HEIRLOOMS).size();
    p_UpgradeLevel = std::min(p_UpgradeLevel, (uint8)p_HeirloomEntry->MaxHeirloomUpgrade);
    uint32 l_HeirloomFlags = (1 << p_UpgradeLevel) - 1;

    SetDynamicValue(PLAYER_DYNAMIC_FIELD_HEIRLOOMS, l_Index, p_HeirloomEntry->ItemID);
    SetDynamicValue(PLAYER_DYNAMIC_FIELD_HEIRLOOM_FLAGS, l_Index, l_HeirloomFlags);

    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COLLECT_HEIRLOOMS, l_Index + 1);

    if (!sWorld->CanBeSaveInLoginDatabase())
        return true;

    uint32 l_GroupRealmMask = sWorld->getIntConfig(WorldIntConfigs::CONFIG_ACCOUNT_BIND_GROUP_MASK);
    if (p_UseShopGroupRealmMask)
        l_GroupRealmMask = sWorld->getIntConfig(WorldIntConfigs::CONFIG_ACCOUNT_BIND_SHOP_GROUP_MASK);

    PreparedStatement* l_Statement = LoginDatabase.GetPreparedStatement(LOGIN_INS_HEIRLOOM);
    l_Statement->setUInt32(0, GetSession()->GetAccountId());
    l_Statement->setUInt32(1, p_HeirloomEntry->ID);
    l_Statement->setUInt32(2, l_HeirloomFlags);
    l_Statement->setUInt32(3, l_GroupRealmMask);
    l_Statement->setUInt32(4, l_GroupRealmMask);
    LoginDatabase.Execute(l_Statement);

    return true;
}

bool Player::HasHeirloom(uint32 p_ItemID) const
{
    HeirloomEntry const* l_Heirloom = GetHeirloomEntryByItemID(p_ItemID);
    return HasHeirloom(l_Heirloom);
}

bool Player::HasHeirloom(HeirloomEntry const* p_HeirloomEntry) const
{
    if (!p_HeirloomEntry)
        return false;

    std::vector<uint32> const& l_Heirlooms = GetDynamicValues(PLAYER_DYNAMIC_FIELD_HEIRLOOMS);

    for (uint32 l_I = 0; l_I < l_Heirlooms.size(); ++l_I)
        if (l_Heirlooms[l_I] == p_HeirloomEntry->ItemID)
            return true;

    return false;
}

void Player::_LoadHeirloomCollection(PreparedQueryResult p_Result)
{
    if (!p_Result)
        return;

    uint32 l_AllowedGroupRealmMask = sWorld->getIntConfig(CONFIG_ACCOUNT_BIND_ALLOWED_GROUP_MASK);

    do
    {
        Field* l_Fields = p_Result->Fetch();

        uint32 l_HeirloomID     = l_Fields[0].GetUInt32();
        uint32 l_HeirloomFlags  = l_Fields[1].GetUInt32();
        uint32 l_GroupRealmMask = l_Fields[2].GetUInt32();

        if ((l_GroupRealmMask & l_AllowedGroupRealmMask) == 0)
            continue;

        HeirloomEntry const* l_HeirloomEntry = sHeirloomStore.LookupEntry(l_HeirloomID);

        if (!l_HeirloomEntry)
            continue;

        if (HasHeirloom(l_HeirloomEntry))
            continue;

        l_HeirloomFlags = std::min(l_HeirloomFlags, (uint32)(1 << l_HeirloomEntry->MaxHeirloomUpgrade) - 1);

        uint32 l_Index = GetDynamicValues(PLAYER_DYNAMIC_FIELD_HEIRLOOMS).size();
        SetDynamicValue(PLAYER_DYNAMIC_FIELD_HEIRLOOMS, l_Index, l_HeirloomEntry->ItemID);
        SetDynamicValue(PLAYER_DYNAMIC_FIELD_HEIRLOOM_FLAGS, l_Index, l_HeirloomFlags);
    }
    while (p_Result->NextRow());

    UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COLLECT_HEIRLOOMS, GetDynamicValues(PLAYER_DYNAMIC_FIELD_HEIRLOOMS).size());
}

uint32 Player::GetHeirloomUpgradeLevel(HeirloomEntry const* p_HeirloomEntry) const
{
    if (!p_HeirloomEntry)
        return 0;

    std::vector<uint32> const& l_Heirlooms = GetDynamicValues(PLAYER_DYNAMIC_FIELD_HEIRLOOMS);

    for (uint32 l_I = 0; l_I < l_Heirlooms.size(); ++l_I)
    {
        if (l_Heirlooms[l_I] == p_HeirloomEntry->ItemID)
        {
            for (int l_X = p_HeirloomEntry->MaxHeirloomUpgrade + 1; l_X != 0; --l_X)
                if (GetDynamicValues(PLAYER_DYNAMIC_FIELD_HEIRLOOM_FLAGS)[l_I] & (1 << (l_X - 1)))
                    return l_X;
            return 0;
        }
    }

    return 0;
}

bool Player::CanUpgradeHeirloomWith(HeirloomEntry const* p_HeirloomEntry, uint32 p_ItemId) const
{
    if (!p_HeirloomEntry)
        return false;

    if (!HasHeirloom(p_HeirloomEntry))
        return false;

    uint32 l_CurrentUpgradeLevel = GetHeirloomUpgradeLevel(p_HeirloomEntry);
    if (p_HeirloomEntry->MaxHeirloomUpgrade <= l_CurrentUpgradeLevel || l_CurrentUpgradeLevel >= MAX_HEIRLOOM_UPGRADE_LEVEL)
        return false;

    if (!p_HeirloomEntry->UpgradeIemBonusID[l_CurrentUpgradeLevel])
        return false;

    if (p_HeirloomEntry->UpgradableByItemID[l_CurrentUpgradeLevel] != p_ItemId)
        return false;

    return HasItemCount(p_ItemId);
}

void Player::SetQuestBit(uint32 p_BitIndex, bool p_Completed)
{
    if (!p_BitIndex)
        return;

    uint32 l_FlagValue  = 1 <<  ((p_BitIndex - 1) % 32);
    uint32 l_FieldIndex = (p_BitIndex - 1) / 32;

    if (p_Completed)
        SetFlag(PLAYER_FIELD_QUEST_COMPLETED + l_FieldIndex, l_FlagValue);
    else
        RemoveFlag(PLAYER_FIELD_QUEST_COMPLETED + l_FieldIndex, l_FlagValue);
}

bool Player::IsQuestBitFlaged(uint32 p_BitIndex) const
{
    if (!p_BitIndex)
        return false;

    uint32 l_FlagValue  = 1 << ((p_BitIndex - 1) % 32);
    uint32 l_FieldIndex = (p_BitIndex - 1) / 32;

    return HasFlag(PLAYER_FIELD_QUEST_COMPLETED + l_FieldIndex, l_FlagValue);
}

void Player::ClearQuestBits(std::vector<uint32> const& p_QuestBits)
{
    for (auto l_Bit : p_QuestBits)
        SetQuestBit(l_Bit, false);
}

Difficulty Player::GetDifficultyID(MapEntry const* p_MapEntry) const
{
    if (!p_MapEntry->IsRaid())
        return m_dungeonDifficulty;

    MapDifficulty const* l_DefaultDifficulty = GetDefaultMapDifficulty(p_MapEntry->MapID);
    if (!l_DefaultDifficulty)
        return m_LegacyRaidDifficulty;

    DifficultyEntry const* l_Difficulty = sDifficultyStore.LookupEntry(l_DefaultDifficulty->DifficultyID);
    if (!l_Difficulty || l_Difficulty->Flags & DIFFICULTY_FLAG_LEGACY)
        return m_LegacyRaidDifficulty;

    return m_raidDifficulty;
}

Difficulty Player::CheckLoadedDungeonDifficultyID(Difficulty difficulty)
{
    DifficultyEntry const* l_DifficultyEntry = sDifficultyStore.LookupEntry(difficulty);
    if (!l_DifficultyEntry)
        return DifficultyNormal;

    if (l_DifficultyEntry->InstanceType != MAP_INSTANCE)
        return DifficultyNormal;

    if (!(l_DifficultyEntry->Flags & DIFFICULTY_FLAG_CAN_SELECT))
        return DifficultyNormal;

    return difficulty;
}

Difficulty Player::CheckLoadedRaidDifficultyID(Difficulty p_Difficulty)
{
    DifficultyEntry const* l_DifficultyEntry = sDifficultyStore.LookupEntry(p_Difficulty);
    if (!l_DifficultyEntry)
        return DifficultyRaidNormal;

    if (l_DifficultyEntry->InstanceType != MAP_RAID)
        return DifficultyRaidNormal;

    if (!(l_DifficultyEntry->Flags & DIFFICULTY_FLAG_CAN_SELECT) || (l_DifficultyEntry->Flags & DIFFICULTY_FLAG_LEGACY))
        return DifficultyRaidNormal;

    return p_Difficulty;
}

Difficulty Player::CheckLoadedLegacyRaidDifficultyID(Difficulty p_Difficulty)
{
    DifficultyEntry const* l_DifficultyEntry = sDifficultyStore.LookupEntry(p_Difficulty);
    if (!l_DifficultyEntry)
        return Difficulty10N;

    if (l_DifficultyEntry->InstanceType != MAP_RAID)
        return Difficulty10N;

    if (!(l_DifficultyEntry->Flags & DIFFICULTY_FLAG_CAN_SELECT) || !(l_DifficultyEntry->Flags & DIFFICULTY_FLAG_LEGACY))
        return Difficulty10N;

    return p_Difficulty;
}

void Player::ApplyWargameItemModifications()
{
    bool l_InWargame       = GetBattleground() && GetBattleground()->IsWargame();
    bool l_TournamentRules = GetBattleground() && GetBattleground()->UseTournamentRules();

    for (uint8 l_I = 0; l_I < EQUIPMENT_SLOT_END; ++l_I)
    {
        if (Item* l_Item = m_items[l_I])
        {
            bool l_UpdateItemMods = false;

            if (l_InWargame)
            {
                if (l_Item->GetTemplate()->Flags3 & ItemFlags3::ITEM_FLAG3_WARGAME_ONLY)
                {
                    if (l_Item->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE))
                    {
                        l_Item->RemoveFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE);
                        l_UpdateItemMods = true;
                    }
                }
                else if (l_TournamentRules && !l_Item->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE))
                {
                    l_Item->SetFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE);
                    l_UpdateItemMods = true;
                }
            }
            else
            {
                if (l_Item->GetTemplate()->Flags3 & ItemFlags3::ITEM_FLAG3_WARGAME_ONLY)
                {
                    if (!l_Item->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE))
                    {
                        l_Item->SetFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE);
                        l_UpdateItemMods = true;
                    }
                }
                else if (l_Item->HasFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE))
                {
                    l_Item->RemoveFlag(ITEM_FIELD_DYNAMIC_FLAGS, ItemFieldFlags::ITEM_FIELD_FLAG_DISABLE);
                    l_UpdateItemMods = true;
                }
            }

            if (l_UpdateItemMods)
            {
                _ApplyItemMods(l_Item, l_I, false);
                _ApplyItemMods(l_Item, l_I, true);
            }
        }
    }
}

void Player::RewardCompletedAchievementsIfNeeded()
{
    GetAchievementMgr().GetCompletedAchievementLock().acquire();
    for (auto l_Iterator : GetAchievementMgr().GetCompletedAchivements())
    {
        AchievementEntry const* l_Achievement = sAchievementMgr->GetAchievement(l_Iterator.first);
        if (l_Achievement == nullptr)
            continue;

        /// Make sure the achievement is for the right faction
        if ((GetTeamId() == TeamId::TEAM_HORDE && l_Achievement->Faction == 1)
            || (GetTeamId() == TeamId::TEAM_ALLIANCE && l_Achievement->Faction == 0))
            continue;

        AchievementReward const* l_Reward = sAchievementMgr->GetAchievementReward(l_Achievement);
        if (l_Reward == nullptr)
            continue;

        /// Titles are already handle at achievement loading
        /// So we just handle item case here
        if (l_Reward->itemId == 0)
            continue;

        ItemTemplate const* l_ItemTemplate = sObjectMgr->GetItemTemplate(l_Reward->itemId);
        if (l_ItemTemplate == nullptr)
            continue;

        uint32 l_SpellLearned = 0;
        for (uint8 l_Index = 0; l_Index < MAX_ITEM_PROTO_SPELLS; ++l_Index)
        {
            if (l_ItemTemplate->Spells[l_Index].SpellTrigger == ItemSpelltriggerType::ITEM_SPELLTRIGGER_LEARN_SPELL_ID)
            {
                l_SpellLearned = l_ItemTemplate->Spells[l_Index].SpellId;
                break;
            }
        }

        /// Hack fix for Chauffeured Chopper, item sent is a gift box, containing Horde or Alliance chopper, so no learned spell
        if (l_ItemTemplate->ItemId == 122718)
        {
            switch (GetTeamId())
            {
                case TeamId::TEAM_ALLIANCE:
                {
                    l_SpellLearned = 179245;
                    break;
                }
                case TeamId::TEAM_HORDE:
                {
                    l_SpellLearned = 179244;
                    break;
                }
                default:
                    break;
            }
        }

        /// - Only support mount / pet items
        /// - Because we have not way to know if the player have already get the reward otherwise
        if (!l_SpellLearned)
            continue;

        /// Check if the player have already get the reward
        /// 1 - Check if player already have learned the spell
        if (HasSpell(l_SpellLearned))
            continue;

        /// 2 - Check his bags / bank
        if (GetItemCount(l_ItemTemplate->ItemId, true) != 0)
            continue;

        /// 3 - Check in mail (achievements rewards are sended by mails)
        {
            bool l_FoundInMail = false;
            for (auto l_Item : mMitems)
            {
                if (l_Item.second->GetEntry() == l_ItemTemplate->ItemId)
                {
                    l_FoundInMail = true;
                    break;
                }
            }

            if (l_FoundInMail)
                continue;
        }

        /// We are now sure the player didn't get the reward, send it to him with mail!
        // Mail
        if (l_Reward->sender)
        {
            Item* l_Item = l_Reward->itemId ? Item::CreateItem(l_Reward->itemId, 1, this) : nullptr;

            int l_LocIDX = GetSession()->GetSessionDbLocaleIndex();

            // Subject and text
            std::string l_Subject = l_Reward->subject;
            std::string l_Text = l_Reward->text;
            if (l_LocIDX >= 0)
            {
                if (AchievementRewardLocale const* l_Locale = sAchievementMgr->GetAchievementRewardLocale(l_Achievement))
                {
                    ObjectMgr::GetLocaleString(l_Locale->subject, l_LocIDX, l_Subject);
                    ObjectMgr::GetLocaleString(l_Locale->text, l_LocIDX, l_Text);
                }
            }

            MailDraft l_Draft(l_Subject, l_Text);

            SQLTransaction l_Transaction = CharacterDatabase.BeginTransaction();
            if (l_Item)
            {
                // Save new item before send
                l_Item->SaveToDB(l_Transaction);                               // Save for prevent lost at next mail load, if send fail then item will deleted

                // Item
                l_Draft.AddItem(l_Item);
            }

            l_Draft.SendMailTo(l_Transaction, this, MailSender(MAIL_CREATURE, l_Reward->sender));
            CharacterDatabase.CommitTransaction(l_Transaction);
        }
    }
    
    GetAchievementMgr().GetCompletedAchievementLock().release();
}

void Player::DeleteInvalidSpells()
{
    PlayerSpellMap l_SpellMap = GetSpellMap();
    for (PlayerSpellMap::const_iterator l_Iterator = l_SpellMap.begin(); l_Iterator != l_SpellMap.end(); ++l_Iterator)
    {
        if (sObjectMgr->IsInvalidSpell(l_Iterator->first))
            removeSpell(l_Iterator->first, false, false);
    }
}

uint32 Player::GetDefaultSpecId() const
{
    ChrClassesEntry const* l_CharClasseEntry = sChrClassesStore.LookupEntry(getClass());
    if (l_CharClasseEntry)
        return l_CharClasseEntry->m_DefaultSpec;
    return 0;
}

void Player::_LoadWorldStates(PreparedQueryResult p_Result)
{
    if (!p_Result)
        return;

    do
    {
        Field* l_Fields = p_Result->Fetch();
        CharacterWorldState l_WorldState;
        l_WorldState.Value   = l_Fields[1].GetUInt64();
        l_WorldState.Changed = false;

        m_CharacterWorldStates.insert(std::make_pair(l_Fields[0].GetUInt32(), l_WorldState));
    }
    while (p_Result->NextRow());
}

void Player::_SaveCharacterWorldStates(SQLTransaction& p_Transaction)
{
    for (auto l_Iterator : m_CharacterWorldStates)
    {
        CharacterWorldState& l_WorldState = l_Iterator.second;
        if (!l_WorldState.Changed)
            continue;

        PreparedStatement* l_Statement = CharacterDatabase.GetPreparedStatement(CHAR_REP_WORLD_STATES);
        l_Statement->setUInt32(0, GetGUIDLow());
        l_Statement->setUInt32(1, l_Iterator.first);
        l_Statement->setUInt64(2, l_WorldState.Value);

        p_Transaction->Append(l_Statement);
    }
}

void Player::SendCustomMessage(std::string const& p_Opcode)
{
    std::ostringstream l_Message;
    l_Message << p_Opcode << "|" << " " << "|";
    ChatHandler(this).SendSysMessage(l_Message.str().c_str());
}
void Player::SendCustomMessage(std::string const& p_Opcode, std::ostringstream const& p_Message)
{
    std::ostringstream l_Message;
    l_Message << p_Opcode << "|" << p_Message.str() << "|";
    ChatHandler(this).SendSysMessage(l_Message.str().c_str());
}
void Player::SendCustomMessage(std::string const& p_Opcode, std::vector<std::string> const& p_Data)
{
    std::ostringstream l_Message;
    l_Message << p_Opcode << "|";

    if (!p_Data.empty())
    {
        for (auto const& l_Elem : p_Data)
            l_Message << l_Elem << "| ";
    }
    else
        l_Message << " " << "|";

    ChatHandler(this).SendSysMessage(l_Message.str().c_str());
}

uint32 Player::GetBagsFreeSlots() const
{
    uint32 l_FreeBagSlots = 0;

    for (uint8 l_I = INVENTORY_SLOT_BAG_START; l_I < INVENTORY_SLOT_BAG_END; l_I++)
    {
        if (Bag * l_Bag = GetBagByPos(l_I))
            l_FreeBagSlots += l_Bag->GetFreeSlots();
    }

    for (uint8 l_I = INVENTORY_SLOT_ITEM_START; l_I < INVENTORY_SLOT_ITEM_END; l_I++)
    {
        if (!GetItemByPos(INVENTORY_SLOT_BAG_0, l_I))
            ++l_FreeBagSlots;
    }

    return l_FreeBagSlots;
}

void Player::CheckTalentSpells()
{
    std::set<uint32> l_Talents;
    uint8 l_SpeCount = std::min(GetSpecsCount(), (uint8)MAX_TALENT_SPECS);

    for (uint8 l_SpecIdx = 0; l_SpecIdx < l_SpeCount; l_SpecIdx++)
    {
        PlayerTalentMap& l_PlayerTalent = *GetTalentMap(l_SpecIdx);
        for (PlayerTalentMap::iterator l_TalentItr = l_PlayerTalent.begin(); l_TalentItr != l_PlayerTalent.end(); ++l_TalentItr)
            l_Talents.insert(l_TalentItr->first);
    }

    for (PlayerSpellMap::iterator l_Itr = m_spells.begin(); l_Itr != m_spells.end();)
    {
        if (!l_Itr->second)
            continue;

        if (l_Itr->second->state != PlayerSpellState::PLAYERSPELL_REMOVED
            && sSpellMgr->IsTalent(l_Itr->first)
            && l_Talents.find(l_Itr->first) == l_Talents.end())
        {
            removeSpell(l_Itr->first);
            l_Itr = m_spells.begin();
            continue;
        }

        ++l_Itr;
    }
}

void Player::HandleWarlockWodPvpBonus()
{
    if (getClass() != CLASS_WARLOCK || getLevel() != 100)
        return;

    uint32 l_SpellBonusId = 0;
    uint32 l_TriggerSpell = 0;

    /// Check what's specialization bonus we need
    if (GetSpecializationId() == SPEC_WARLOCK_AFFLICTION)
    {
        l_SpellBonusId = 171377;
        l_TriggerSpell = 171378;
    }
    else if (GetSpecializationId() == SPEC_WARLOCK_DESTRUCTION)
    {
        l_SpellBonusId = 171383;
        l_TriggerSpell = 188168;
    }

    if (HasAura(l_SpellBonusId) && !HasSpellCooldown(l_TriggerSpell))
    {
        CastSpell(this, l_TriggerSpell, true);
        AddSpellCooldown(l_TriggerSpell, 0, 15 * IN_MILLISECONDS);
    }
}

uint32 Player::GetRandomWeaponFromPrimaryBag(ItemTemplate const* p_Transmogrified) const
{
    uint32 l_AllItemsInPrimaryBag[16];
    uint8 l_ArrayCapacity = 0;

    for (uint8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
    {
        if (Item* l_FoundItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
        {
            if (ItemTemplate const* l_FoundItemTemplate = l_FoundItem->GetTemplate())
            {
                if (l_FoundItemTemplate->Class != ITEM_CLASS_WEAPON)
                    continue;

                if (!Item::CanTransmogrifyIntoRandomWeapon(l_FoundItemTemplate, p_Transmogrified))
                    continue;

                if (l_FoundItemTemplate->ItemId != 0)
                {
                    l_AllItemsInPrimaryBag[l_ArrayCapacity] = l_FoundItemTemplate->ItemId;
                    l_ArrayCapacity++;
                }
            }
        }
    }

    /// If we have just one item, we should take it
    if (l_ArrayCapacity == 1)
        return l_AllItemsInPrimaryBag[0];

    /// Select random weapon id from primary bag if we have many items
    if (l_ArrayCapacity > 1)
    {
        int32 l_RandomWeapon = urand(0, l_ArrayCapacity - 1);
        return l_AllItemsInPrimaryBag[l_RandomWeapon];
    }

    return 0;
}

uint32 Player::GetZoneId(bool p_ForceRecalc) const
{
    if (p_ForceRecalc)
        *(const_cast<uint32*>(&m_LastZoneId)) = WorldObject::GetZoneId();

    return m_LastZoneId;
}

uint32 Player::GetAreaId(bool p_ForceRecalc) const
{
    if (p_ForceRecalc)
        *(const_cast<uint32*>(&m_LastAreaId)) = WorldObject::GetAreaId();

    return m_LastAreaId;
}

void Player::GetZoneAndAreaId(uint32& p_ZoneId, uint32& p_AreaId, bool p_ForceRecalc) const
{
    if (p_ForceRecalc)
    {
        WorldObject::GetZoneAndAreaId(p_ZoneId, p_AreaId);
        *(const_cast<uint32*>(&m_LastZoneId)) = p_ZoneId;
        *(const_cast<uint32*>(&m_LastAreaId)) = p_AreaId;
        return;
    }

    p_ZoneId = m_LastZoneId;
    p_AreaId = m_LastAreaId;
}